Access selected items in ListView when the button is clicked
I have a
ListViewwitch uses my own
QQmlApplicationEngine engine; engine.rootContext()->setContextProperty("carListModel", &carListModel);
User can select multiple items and then click a button. When he clicks the button I want to access all the selected items from the c++ code. Can someone tell me how can I achieve that? The part with the button is obvious (signals) but the part where I access the
ListViewfrom the c++ is not clear for me.
The ListView is an arbitrary
ListViewwith assigned model.
I've read the http://doc.qt.io/qt-5/qtqml-cppintegration-interactqmlfromcpp.html, but there is a Warning mentioned that the the
QObject *rect = object->findChild<QObject*>("rect");should not be used as it breaks the QML<->c++ logic.
The best would be to set that in the model itself and access it from C++.
Assuming you have for eg.
carListModel, you can add a setter and getter function to it. The setter ( say
setSelected(bool)) can be made
Q_INVOKABLEwhich will be accessed from QML to set that it is selected. Then just you need to access all these
CarItem's from C++ and check if they are selected using getter.
I think there is no way to make a QML ListView multi-selectable.
But you can do something like that:
if an element is clicked:
- set its property selected (or however you call it), and
- set in delegate that if selected is true, then it should be formatted differently. for example the background color changes to yellow.
- then add it to a list e.g QList of selected items. You can create a property for this in C++
Later you can get a list of selected items and can handle with this.