[SOLVED] How do I get role names and count from ListElements inside a ListModel
-
Hi everyone,
I'm trying to get some information about a ListModel and its ListElements, when it's dynamically created and I don't really know the contents.
Let's use the example from the ListElement documentation:
@ListModel {
id: fruitModelListElement { name: "Apple" cost: 2.45 } ListElement { name: "Orange" cost: 3.25 } ListElement { name: "Banana" cost: 1.95 }
}@
Now I want to access several things:
How many elements are in the list model- I know I can do this with fruitModel.count. So that's solved.
Get each individual list element
- Using a for loop with the count information and fruitModel.get(i) solves this.
But now let's assume, I don't know what's inside of the list elements and that's where I'm stuck. I want to get the count of the elements inside of the list element and their role names, so I can access their values.
Using the above example I want to get count = 2 and role names = name and cost
Is there some way to achieve this? Doesn't matter if it's inside QML or C++
Thanks in advance!
-
I do not know of any way to do that with ListModel and ListElement. So if you really need this method then you should make your own model based on "QAbstractListModel":http://qt-project.org/doc/qt-5/qabstractlistmodel.html.
-
Hi,
You can get the roles from C++, since ListModel is of type QAbstractItemModel you can find it accordingly using the objectName property.
Going thru your above example
@
ListModel {
id: fruitModel
objectName: "mymodel"
ListElement {
name: "Apple"
cost: 2.45
}
ListElement {
name: "Orange"
cost: 3.25
}
ListElement {
name: "Banana"
cost: 1.95
}
}
@Then from C++, assuming you are using QQuickView
@
QQuickView view;
QAbstractItemModel item = view.rootObject()->findChild<QAbstractItemModel>("mymodel");
qDebug() << item->roleNames().value(0); //gives the role at 0
@Since "roleNames":http://qt-project.org/doc/qt-5/qabstractitemmodel.html#roleNames returns a Hash key-value pair, you can iterate it and get the roles, count etc..
Is this what you require ?