Updating ListView using JS object model
-
Given a simple QML ListView using an object-based model, is there any way to force updates to the model, that will propagate to changes in the delegates?
For example, let's say I have a list with model like below, and I want the
ct
property to increment when I click on a button, and have that reflected in the button label:ListView { id: mylist model: [ {n:"a", ct:0}, {n:"b", ct:0} ] delegate: Button { text: modelData.n + modelData.ct onClicked: { modelData.ct++; console.log(JSON.stringify(mylist.model)) } } }
The code above constantly outputs the original model (where
ct
is 0) on each click. Same if I attempt to force a change like:mylist.model[index].ct += 1
.How can I change the model (without using a
ListModel
, which does not support nested data structures I am currently using)? -
Given a simple QML ListView using an object-based model, is there any way to force updates to the model, that will propagate to changes in the delegates?
For example, let's say I have a list with model like below, and I want the
ct
property to increment when I click on a button, and have that reflected in the button label:ListView { id: mylist model: [ {n:"a", ct:0}, {n:"b", ct:0} ] delegate: Button { text: modelData.n + modelData.ct onClicked: { modelData.ct++; console.log(JSON.stringify(mylist.model)) } } }
The code above constantly outputs the original model (where
ct
is 0) on each click. Same if I attempt to force a change like:mylist.model[index].ct += 1
.How can I change the model (without using a
ListModel
, which does not support nested data structures I am currently using)?@Phrogz hi,
this way the ct value is incremented but model is not updating (refreshing)
ListModel { id: _model ListElement { n: "a" ct: 0 } ListElement { n: "b" ct: 0 } } ListView { id: mylist anchors.fill: parent model: _model delegate: Button { height: 20 width: 50 text: _model.get(0).n + _model.get(0).ct onClicked: { console.log(_model.get(0).ct += 1) } } }
i think this is bad but :
onClicked: { var _ct = _model.get(0).ct _model.clear() _model.append({"n":"a", "ct": _ct+1}) }
This can help more efficiently https://doc-snapshots.qt.io/qt5-5.9/qml-qtqml-models-listmodel.html#using-threaded-list-models-with-workerscript