动态创建 QML ListElement 和内容 [英] Dynamically create QML ListElement and content

查看:18
本文介绍了动态创建 QML ListElement 和内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图在 ListModel 中动态创建 ListElements.这工作正常,直到我尝试在 ListElements 中编写一些内容以动态加载.

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.

我尝试使用 ListElement 和小时作为属性创建一个自己的文件,但是模型然后我收到一个错误,说 ListElements 不能嵌套.

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?

代码:

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

将函数中的代码行改为:

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.

推荐答案

我不知道为什么这不起作用,但使用普通的旧 JavaScript 对象就可以了:

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

这篇关于动态创建 QML ListElement 和内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆