gpt4 book ai didi

qt - 如何将项目添加到数组 qml?

转载 作者:行者123 更新时间:2023-12-05 04:04:19 25 4
gpt4 key购买 nike

我有:

MyItem.qml

import QtQuick 2.0
Item {
property string info1: "info"
property int info2: 1
}

如何在初始化期间向数组 qml 添加项目?

这是工作:

import QtQuick 2.0
Item {
property var arr: [{ info1: "test", info2: 1}, { info1: "info" }]
}

但是,这是行不通的:

import QtQuick 2.0
Item {
property var arr: [MyItem { info1: "test", info2: 1}, MyItem { info1: "info" }]
}

最佳答案

如果您使用更新的 QML 版本,您可以使用新的 list<Item> - 属性类型。您可以在那里轻松地以您想要的语法添加项目 - 就像您使用 property alias someProperty: someItem.somePropertyList (e.g. children) 时一样例如。

include QtQuick 2.10 // I think 2.9 is sufficient
ApplicationWindow {
...
property list<Item> myItemList: [
Item { Component.onCreated: console.log(parent) }, // parent will be null! Set it explicitly if needed.
Item {},
Item {},
...
]
}

http://doc.qt.io/qt-5/qml-list.html

文档中的小注释:

Note: The list type is not recommended as a type for custom properties. The var type should be used instead for this purpose as lists stored by the var type can be manipulated with greater flexibility from within QML.

恕我直言,只要您不需要“更大的灵 active ”,您就可以忽略它


在旧版本中这是不可能的,但如果你有一个类型“ArrayObject.qml”,你可以绕过它

import QtQuick 2.0

QtObject {
id: root
default property QtObject store
readonly property var arr: (arr === undefined ? [] : arr) // This will give you a binding loop, but ensures that after filling the array, it is not reset to [].
onStoreChanged: {
if (store) {
console.log(store)
arr[arr.length] = store
console.log(arr, arr.length)
}
store = null
}
}

然后您可以使用它:

ArrayObject {
id: tst
Item {
}
Item {
}
Item {
}
}

当然,可能还有其他解决方法。

例如:

Item {
property var myArray: [
itemId1, itemId2, itemId3, itemId4
]
Item { id: itemId1 }
...
}

关于qt - 如何将项目添加到数组 qml?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52760931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com