Question

I got a fonctionnal ListModel defined like this :

ListModel {
    id: leftGrid
    ListElement { icon: "Images/1.png" }
    ListElement { icon: "Images/2.png" }
}

The thing is that I'd like to define ListElement in separate qml files but I really don't know how to do it...

I wrote the qml like this :

//myWidget.qml
import QtQuick 1.0

ListElement {
    icon: "Images/X.png"
}

But I don't know how to "invoke" or "instanciate" it in my main file...

I tried :

ListModel {
    id: leftGrid
    ListElement { icon: "Images/1.png" }
    myWidget //qml file
}

and :

ListModel {
    id: leftGrid
    ListElement { icon: "Images/1.png" }
    ListElement { myWidget }
}

Both doesn't work...

Any help with be welcomed, thanks in advance.

Was it helpful?

Solution

I don't think it's possible to have ListElements as separate files. This is because when you do that you are implicitly creating a Component, with your contents inside (in this case the ListElement). However the ListModel can only accept ListElements as its children, not Components with nested ListElements inside.

What you can do however to dynamically define your model items is to declare a ListModel, then add your data via a piece of javascript, for example in your Component.onCompleted handler.

If you look at the API for ListModel you will see it has an append() method, among others. You can pass a JS dictionary to this method and it will add a new ListElement to the list and populate its properties according to the dictionary.

Example:

import QtQuick 1.0

Rectangle {
    width: 360
    height: 360

    ListView {
        id:list
        anchors.fill: parent
        model: ListModel {
            ListElement { foo: "hello" }
        }
        delegate: Text {
            text: foo
            width: ListView.view.width
        }

        Component.onCompleted: {
            list.model.append({ "foo": "world" })
        }
    }
}

Your list will appear with two items in it: "hello" and "world"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top