【发布时间】:2012-09-10 17:47:55
【问题描述】:
我真的很喜欢 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!"
}
}
但我看到了以下限制:我只能定义一个按钮模板带有一些属性,而不是带有一些占位符。实例中定义的所有子代都将是直接子代,至少在默认情况下,我想更改此行为。
假设我想在按钮中放置一个项目(假设是一个图像,但我不想告诉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 实例移动到占位符中,然后父锚点应该是占位符项的那些,而不是模板项。
【问题讨论】: