我真的很喜欢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
的方法。需要注意的是,在我的情况下,这些内容以后永远不会改变(至少在应用程序的当前设计中...)。
此外,我希望锚定在占位符内起作用。例如,如果我将内容定义为文本元素,并使其居中于其父元素中(该父元素首先将是模板本身)。然后,我的代码将此文本实例移动到占位符中,父级锚点应该是占位符项的锚点,而不是模板项的锚点。