ListView with ObjectModel and custom objects get index of selected object
-
wrote on 3 May 2022, 08:26 last edited by
Hello!
Is it possible to get the index of the selected item in an ObjectModel that is displayed with an ListView?
For example:
// A.qml Item { id: itemA property string name; Text { text: "A:" + name } } // B.qml Item { id: itemB property string name; Text { text: "B:" + name } } //List.qml ListView { property var objects; id: listViewExample model: objects } // main.qml List { objects: ObjectModel { A { name: "test"} B { name: "test"} } }
The reason is that i want to create multiple objects that can be displayed on one list, but each of them have a slightly different behaviour when clicked etc. This is a bit oversimplyfied here in this example.
However, the question remains. How can I get the index of the object in the components A and B in the custom implementation in files A.qml and B.qml. Note: the objects A and B should only be used in combo with the custom listview in List.qml (that is the goal at least)
Or from another perspective, how do I implement this cleanly to have a set of custom components in a list that notifies the above Listview when the custom component is clicked? The listview is displayed on a touchscreen that will scroll trough the list of items. And I want it to scroll to the selected item when selected.
-
wrote on 4 May 2022, 21:39 last edited by
I don't know why it doesn't say in the ListView docs, but you can use the "index" variable inside a delegate. I would assume you could use that in your A or B object inside an ObjectModel. I know you can use "index" inside a regular delegate.
-
wrote on 24 Jul 2024, 06:58 last edited by
I stumpled across this thread.
The answer is quite simple:Item { id: itemA property string name; Text { text: "A: name:" + itemA.name + " index:" + itemA.ObjectModel.index; } }