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

Improve documentation on interaction between models and delegates

    XMLWordPrintable

Details

    Description

      Consider:

      import QtQuick 2.15
      import QtQuick.Window 2.15
      import QtQuick.Controls 2.15
      import QtQuick.Layouts 1.15
      
      Window {
          id: window
          width: 300
          height: 500
          visible: true
          property list<int> a: [1, 2, 3, 4, 5, 6]
          RowLayout {
              anchors.fill: parent
              ListView {
                  Layout.fillHeight: true
                  model: a
                  delegate: Button {
                      text: modelData
                      onClicked: {
                          a[index] = modelData + 1;
                          console.log("a is now", a)
                      }
                  }
              }
              ListView {
                  id: l
                  Layout.fillHeight: true
                  model: a
                  delegate: Button {
                      text: modelData
                      onClicked: {
                          model.modelData = modelData + 1;
                          console.log("a is now", l.model, modelData);
                      }
                  }
              }
          }
      }
      

      If you click a button on the left, the label on the button is successfully updated but the console.log produces a ReferenceError. Apparently 'a' disappears in the process of writing to it. The ReferenceError goes away if you use an untyped "var" property for a, but then the value is not propagated. The latter is because JavaScript arrays are not reference objects and don't signal their properties when they are changed.

      The buttons on the right also update their labels and the internal model of the ListView, but understandably don't write back to the original list, since that got detached when assigning to the model. Views generally only write back to adapted models if those have a separate identity and aren't copied on assignment. This should be documented.

      Attachments

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

        Activity

          People

            ulherman Ulf Hermann
            ulherman Ulf Hermann
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

            Dates

              Created:
              Updated:

              Gerrit Reviews

                There are no open Gerrit changes