Uploaded image for project: 'Qt'
  1. Qt
  2. QTBUG-65892

Pitfalls of using array as a model are not documented

    XMLWordPrintable

Details

    Description

      It's known - but not documented - that using an array as a model for views in Qt Quick is a bad idea. The view won't be updated when such a model is changed, as attempts to modify the array have no effect at all:

      import QtQuick 2.7
      import QtQuick.Controls 2.2
      
      ApplicationWindow {
          width: 640
          height: 480
          visible: true
      
          ListView {
              id: listView
              anchors.fill: parent
              clip: true
      
              model: ["a", "b", "c"]
              delegate: Row {
                  spacing: 10
      
                  Label {
                      text: modelData
                  }
                  Button {
                      text: "Modify"
                      onClicked: {
                          listView.model[index] = "modified"
                          print(JSON.stringify(listView.model))
                      }
                  }
                  Button {
                      text: "Remove"
                      onClicked: {
                          listView.model.splice(index, 1)
                          print(JSON.stringify(listView.model))
                      }
                  }
              }
          }
      }
      

      Interestingly though, stepping through http://code.qt.io/cgit/qt/qtdeclarative.git/tree/src/qml/jsruntime/qv4arrayobject.cpp#n520 on the code above shows that the array is actually spliced, so.. not sure what happens there.

      When QTBUG-65890 is fixed, there should be a part that states that JavaScript arrays are only useful as read-only models, and that ListModel or a proper C++ model should be used if the model needs to be modified.

      Attachments

        Issue Links

          No reviews matched the request. Check your Options in the drop-down menu of this sections header.

          Activity

            People

              docteam Qt Documentation Team
              mitch_curtis Mitch Curtis
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

              Dates

                Created:
                Updated:

                Gerrit Reviews

                  There are no open Gerrit changes