Dynamically create QML ListElement and content

て烟熏妆下的殇ゞ 提交于 2020-01-22 17:55:47

问题


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:


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"
            };
        }
    }
}


来源:https://stackoverflow.com/questions/27902535/dynamically-create-qml-listelement-and-content

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!