[SOLVED] Create a ListModel with Objects and lists (QML)



  • 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?



  • The documentation explains this: http://qt-project.org/doc/qt-5.0/qtqml/qml-qtquick2-listmodel.html#example-usage

    @
    ListModel {
    id: customerModel

    ListElement {
        name: "John"
        products: [
            ListElement { name: "P1";  price:  4.96 },
            ListElement { name: "P2";  price:  5.82 }
        ]
    }    
    

    }
    @



  • 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 =)



  • 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;
    }@


  • 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: []
    }
    }
    @



  • You should even be able to have a complete empty ListModel;

    @
    ListModel{
    id: myListModel
    }@


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.