[英]How do you assign a QML Item to a component property in QML and then use that object inside the component?
我正在尝试创建一个QML对象,其作用类似于其他对象的包装器。 这是我的QML文件(Container.qml):
Item {
property string label
property Item control
Row {
Label {
text: label
}
// Not sure how to display the control assigned to the control property
}
}
我想做什么(在我的QML中使用这个组件)是这样的:
Container {
label: "My Label"
control: Textbox {
text: "My Value"
}
}
当输入QML时,结果(在界面中)应该类似于此QML的输出:
Item {
Row {
Label {
text: "My Label"
}
Textbox {
text: "My Value"
}
}
}
这可能吗? 当我尝试这样做时,在将一个Item分配给control属性时,我得到“无法将对象分配给属性”。 我搜索了Qt论坛并无情地搜索了这个,但没有成功。 如果有人知道答案,我将不胜感激。
谢谢
插口
有更好的解决方案:
/* MyObject.qml */
Rectangle {
default property alias data /* name can be any */ : inner_space.data
/* ... You can put other elements here ... */
Item {
id: inner_space
/* ... Params ... */
}
/* ... You can put other elements here ... */
}
现在我们可以做我们想要的一切!
/* main.qml */
Rectangle {
MyObject {
Button {
/* ... */
}
}
}
感谢用户bobbaluba建议使用data
属性而不是children
。
您可以使用自定义属性为其他项创建容器:
Item
{
id: root
property list<Item> rectList: [
Rectangle
{
parent: root
},
Rectangle
{
parent: root
},
Rectangle
{
parent: root
},
Rectangle
{
parent: root
}
]
}
请注意,矩形项的父项是手动设置的,因此它们将是容器的可视子项。
您可以将它们评估为javascript数组
for ( var i = 0; i < root.rectList.length; i++ )
{
var rect = root.rectList[i];
rect.visible = true;
}
要么
rect.rectList[1].visible = false;
现在使用QML大约一个月了,我不知道怎么做到这一点我很害怕。
最好的计划是找出控件(示例中的Textbox
)可能存在的所有可能的东西,创建行中每个组件的实例,并在Item
上设置相应的状态。 然后,州将根据需要使所需组件可见或不可见。
编辑
只是觉得。 (还没试过,但试一试!)在你的Item
的Component.onCompleted:
handler中,尝试调用control.createObject(rowID)
,其中rowID
是你的Row
对象的id
,(你想成为父对象) control
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.