我真的很喜欢 QML。我喜欢如何定义组件(类似于类)及其属性,并从其他地方实例化它们(类似于对象)。
我可以定义,比如说,一个按钮,有一些外观和感觉,以及一个标签文本。例如,可以使用此组件定义 (Button.qml
) 来完成此操作:
Item {
id: button
property string label
anchors.fill: parent
Rectangle {
anchors.fill: parent
radius: 10
color: "gray"
Text {
anchors.centerIn: parent
font.pixelSize: 20
text: button.label
color: "white"
}
}
}
并在这个主文件中实例化(
main.qml
):Rectangle {
width: 300
height: 200
Button {
anchors.centerIn: parent
anchors.margins: 50
label: "Hello button!"
}
}
但是我看到了以下限制:我只能定义一个带有一些属性的按钮模板,而不是一些占位符。实例中定义的所有 child 都将是直接 child ,至少在默认情况下,我想改变这种行为。
假设我想在按钮中放置一个项目(假设是一个图像,但我不想告诉
Button
的定义它将是一个图像)。我想象这样的事情:Item {
id: button
property Item contents <-- the client can set the placeholder content here
anchors.fill: parent
Rectangle {
anchors.fill: parent
radius: 10
color: "gray"
Item {
id: placeholder <-- where the placeholder should be inserted
}
}
Component.onCompleted: {
// move the contents into the placeholder...
}
}
我怎样才能做到这一点?不知道有没有用
Component.onCompleted
是正确的方法。但是请注意,在我的情况下,内容之后永远不会改变(至少在我当前的应用程序设计中......)。另外,我希望锚定在占位符内工作。例如,如果我将内容定义为 Text 元素,以它的父元素为中心(首先是模板本身)。然后我的代码将此 Text 实例移动到占位符中,然后父 anchor 应该是占位符项的那些,而不是模板项。
最佳答案
死灵回答,以防其他人像我一样在这里结束。
在 Qt5 中,默认属性变成了“data”,而不是“children”。
这使得添加“项目”以外的其他对象类型成为可能。
例如也可以添加连接(在上面回答我自己的问题)
所以在Qt5中你应该这样做:
Item {
id: button
default property alias contents: placeholder.data
anchors.fill: parent
Rectangle {
anchors.fill: parent
radius: 10
color: "gray"
Item {
id: placeholder <-- where the placeholder should be inserted
}
}
}
请注意:
placeholder.data
而不是 placeholder.children
另请注意,您不必使用别名 contents
- 这可以是你喜欢的任何东西。一个例子:Item {
id: button
default property alias foo: placeholder.data
...
}
关于qt - 如何在 QML 中使用子占位符定义 "template"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12477425/