属性绑定没有按预期工作

时间:2015-10-20 23:33:12

标签: qml qtquick2

我刚刚尝试实现包含复杂数据的列表。在我的情况下,它应该是这样的数组:

[
    { item: "itemName1", objects: [x1,x1,x1] },
    { item: "itemName2", objects: [x2,x2,x2] }
]

据我所知,有两种方法可以做到这一点。首先是将基于QObjectList的模型从C ++暴露给QML。因为我想在纯QML中实现它,所以目前对我不感兴趣。但ListElement的角色必须只包含简单的常量,行字符串,数字等,即没有数组。 所以我将数据源作为外部数组:

import QtQuick 2.5
import QtQuick.Layouts 1.2
import QtQuick.Window 2.0


Window {
    width: 500
    height: 500
    id: window
    ListView {
        id: listView
        anchors.fill: parent
        anchors.margins: 2
        spacing: 2
        property var data: [ { name: "item1", objects: [1,2,3]} ]
        model: data.length
        delegate: Rectangle {
            width: parent.width
            height:  content.height
            property int itemIndex: index
            color: index % 2 ? "#EFEFEF" : "#DEDEDE"
            RowLayout {
                id: content
                spacing: 10
                Text {
                    text: listView.data[itemIndex].name
                }
                Column {
                    Repeater {
                        model: listView.data[itemIndex].objects.length
                        Text {
                            text: listView.data[itemIndex].objects[index]
                        }
                    }
                }
            }
        }
        Component.onCompleted: {
            listView.data.push( { name: "item2", objects: [4,5,6] } );
            listView.data.push( { name: "item3", objects: [7,8,9] } );
            listView.model = listView.data.length; // it doesnt't work without this line
        }
    }
}

它与静态数组一起工作正常。当我动态填充数组时出现问题。在这种情况下,属性绑定(model:data.length)突然停止工作。因此,解决方法是手动设置它,但我不喜欢这个解决方案。

0 个答案:

没有答案