10

So I am trying to dynamically create ListElements in a ListModel. This works fine until I try writing some content in the ListElements to be loaded dynamically.

I tried making an own file with the ListElement within and the hour as a property, but the model then I got an error saying that ListElements can not be nested.

The error for running the code below is:

Cannot assign to non-existent property "hour"

How can I solve this?

Code:

import QtQuick 2.0

ListModel
{
    id: listModel

    Component.onCompleted:
    {
        for (var i = 0; i < 24; i++)
        {
            var object = createListElement(listModel)
        }
    }

    function createListElement(parent)
    {
        var object = Qt.createQmlObject('import QtQuick 2.0; ListElement { hour: "01" }', parent);

        return object;
    }
}

EDIT: Change the code line in the function to:

var object = Qt.createQmlObject('import QtQuick 2.0; ListElement { property string hour: "23" }', parent);

Now I get no errors, but the elements are still not showing in the list.

1 Answer 1

15

I'm not sure why that doesn't work, but using plain old JavaScript objects does the job:

import QtQuick 2.4
import QtQuick.Window 2.0

Window {
    width: 400
    height: 400

    ListView {
        id: listView
        anchors.fill: parent
        model: listModel
        delegate: Rectangle {
            width: listView.width
            height: listView.height / 4

            Text {
                text: hour
                anchors.centerIn: parent
            }
        }
    }

    ListModel {
        id: listModel

        Component.onCompleted: {
            for (var i = 0; i < 24; i++) {
                append(createListElement());
            }
        }

        function createListElement() {
            return {
                hour: "01"
            };
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.