updating ListView based on model changes
Solved
QML and Qt Quick
-
Hi all -
My app needs to do something along these lines:
Window { width: 640 height: 480 visible: true property var myArray: [] ColumnLayout { anchors.fill: parent RoundButton { id: rb height: 40; width: 40 onClicked: { myArray.push("xxx") console.log("myArray size is now " + myArray.length) } } ListView { Layout.fillHeight: true Layout.fillWidth: true model: myArray delegate: Label {text: "added " + index} } } }
In the real app, the additions to the array (model) aren't triggered from a button press, but I don't think that matters. I tried Connections, but that didn't change anything (I really didn't expect it to).
So...what do I need to do in order to get the ListView to update based on changes to the array?
Thanks...
-
import QtQuick 2.15 import QtQuick.Controls 2.15 ApplicationWindow { visible: true width: 400 height: 600 title: "ListView Example" property ListModel myModel: ListModel { ListElement { name: "Item 1" } ListElement { name: "Item 2" } ListElement { name: "Item 3" } } ListView { anchors.fill: parent model: myModel delegate: Item { width: parent.width height: 50 Rectangle { width: parent.width height: 50 color: "lightblue" Text { anchors.centerIn: parent text: model.name } } } } // Add a new element to the model Button { anchors.bottom: parent.bottom text: "Add New Element" onClicked: { myModel.append({name: "New Item"}) } } }
-
M mzimmers has marked this topic as solved on
-
@mzimmers to be more precise : because it is a QAbstractItemModel. You don't have to use ListModel, you can implement one in C++.
https://doc.qt.io/qt-6/qtquick-modelviewsdata-cppmodels.html