我正在尝试创建一个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
}
}
Run Code Online (Sandbox Code Playgroud)
我想做什么(在我的QML中使用这个组件)是这样的:
Container {
label: "My Label"
control: Textbox {
text: "My Value"
}
}
Run Code Online (Sandbox Code Playgroud)
当输入QML时,结果(在界面中)应该类似于此QML的输出:
Item {
Row {
Label {
text: "My Label"
}
Textbox {
text: "My Value"
}
}
}
Run Code Online (Sandbox Code Playgroud)
这可能吗?当我尝试这样做时,在将一个Item分配给control属性时,我得到"无法将对象分配给属性".我搜索了Qt论坛并无情地搜索了这个,但没有成功.如果有人知道答案,我将不胜感激.
谢谢
插口
s.m*_*aks 37
有更好的解决方案:
/* 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 ... */
}
Run Code Online (Sandbox Code Playgroud)
现在我们可以做我们想要的一切!
/* main.qml */
Rectangle {
MyObject {
Button {
/* ... */
}
}
}
Run Code Online (Sandbox Code Playgroud)
感谢用户bobbaluba建议使用该data属性而不是children.
小智 31
您可以使用Loader元素动态加载项目,然后将'control'属性设置为直接引用加载器的sourceComponent属性的别名.
所以你的Container.qml看起来像这样:
Item {
property string label
property alias control : loader.sourceComponent
width: 200; height: 200
Row {
Label { text: label }
Loader { id: loader }
}
}
Run Code Online (Sandbox Code Playgroud)
现在,当您将图形项目分配给"control"属性时,Loader将自动显示该图形项.