Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically create QML ListElement and content

Tags:

qt

qml

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.

like image 701
uniquenamehere Avatar asked Jan 12 '15 12:01

uniquenamehere


1 Answers

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"
            };
        }
    }
}
like image 152
Mitch Avatar answered Nov 08 '22 14:11

Mitch