[SOLVED] How to restore ListView's selected item after the collection (model) changes?
-
Hey there, the title says it all.
I have buttons that add and remove items from the QList<QObject*> that my ListView is bound to. The currentItem of the ListView reverts back to the first item whenever I add or remove items - is there a way to preserve this, at least for additions?
Thanks
-
Hi,
Can you show how do you remove item ? Can you post the code ?
-
The relevant QML looks like this:
@ Button{
width: 100; height: 30
text: "remove"
onClicked: {
myModel.removeThing(myListView.currentIndex)
}
}
...ListView {
id: myListView
anchors.fill: parent
model: myModel.listdelegate: Rectangle { width: 300; height: 30; Text { text: model.modelData.stuff } ..... [logic for selecting items]..... }
}
@
The C++ (within myModel):
@ void removeThing(int index)
{
_list.removeAt(index);
}@where _list is a QList<QObject*> which is exposed as a Q_PROPERTY that 'myListView' binds to.
-
How did you set the currentIndex of the ListView ?
-
So when you add you can "incrementCurrentIndex()":http://qt-project.org/doc/qt-5/qml-qtquick-listview.html#incrementCurrentIndex-method or "decrementCurrentIndex()":http://qt-project.org/doc/qt-5/qml-qtquick-listview.html#decrementCurrentIndex-method on removal.
-
You're welcome :)
You can mark the post as solved. -
bq. just put “[SOLVED]” in the title?
Yes. This is how it works currently :)