[SOLVED] Create a ListModel with Objects and lists (QML)
-
wrote on 23 Oct 2013, 14:02 last edited by
I get some data, which I'd like to show in a ListView. With simple strings, it is not a problem, but with complex data types and lists I cant get it to work.
Here is an example of the data I'd like to display (in json notation):
@
{
"customer": {
"name": "John",
"products": [
{
"name": "p1",
"price": 4.96
},
{
"name": "p2",
"price": 5.82
}
]
}
}
@So I have to put into the ListModel the complex type "customer" with a list of the complex type "products". Any ideas how to solve that problem?
-
wrote on 24 Oct 2013, 09:41 last edited by
The documentation explains this: http://qt-project.org/doc/qt-5.0/qtqml/qml-qtquick2-listmodel.html#example-usage
@
ListModel {
id: customerModelListElement { name: "John" products: [ ListElement { name: "P1"; price: 4.96 }, ListElement { name: "P2"; price: 5.82 } ] }
}
@ -
wrote on 24 Oct 2013, 09:50 last edited by
Yap, thats what the docs say :) But as far as I know, this works only for static content. I couldnt figure out, how to add dynamically content.
For example I tried something like this:
@
ListModel{
id: myListModel
ListElement{
customerName = ""
products = ""
]
}function fillList(){
var listData;
listData = {"customerName" : "John", products = {"name" : "p1", "price" : "4.96"}};
myListModel.append(listData);
}
@But this doesnt work, because the types are not compatible.
Maybe you could tell how to do it the right way, that would help alot =) -
wrote on 24 Oct 2013, 13:28 last edited by
This works:
@ListModel{
id: myListModel
ListElement{
name: "Eddie"
products: [
ListElement{ name: "p0"; price: 3.99 },
ListElement{ name: "p1"; price: 4.96 }
]
}} function fillList(){ var listData; listData = {"name" : "John", "products" : [ {"name" : "p1", "price" : 4.96}, {"name" : "p2", "price" : 5.98} ]}; myListModel.append(listData); label.text = myListModel.get(myListModel.count-1).products.get(0).name; }@
-
wrote on 24 Oct 2013, 13:40 last edited by
Thanks, works great. So I just missed those two brackets, damn it ;)
For others having the same problem: It also works with an empty initial ListModel, you just have to declare the list attribute as list with empty brackets:
@
ListModel{
id: myListModel
ListElement{
name: ""
products: []
}
}
@ -
wrote on 25 Oct 2013, 05:48 last edited by
You should even be able to have a complete empty ListModel;
@
ListModel{
id: myListModel
}@
6/6