将项目添加到自定义组件的布局 [英] Adding Items to a layout of a custom component
问题描述
我有一个自定义的 Footer
Component
我想在我的 QML 应用程序的不同位置重用它:
I have a custom Footer
Component
which I would like to reuse in different place in my QML App:
Rectangle {
color: "gold"
height: 50
anchors {
bottom: parent.bottom
left: parent.left
right: parent.right
}
RowLayout {
anchors.fill: parent
anchors.margins: 10
Button {
text: "quit"
}
}
}
使用起来很简单:
Window {
visible: true
Footer {
}
}
但现在我想在一个视图中为我的 Footer
的 RowLayout
添加一个ButtonA",在另一个视图中添加一个ButtonB".
But now I would like to add a "ButtonA" to the RowLayout
of my Footer
in one view and a "ButtonB" in another view.
我怎样才能做到这一点?
How can I achieve that?
推荐答案
参见 这个 答案.
您必须在 Footer.qml
中声明一个 default
属性:
You have to declare a default
property in Footer.qml
:
import QtQuick 2.0
import QtQuick.Controls 1.2
import QtQuick.Layouts 1.1
Rectangle {
color: "gold"
height: 50
default property alias content: rowLayout.children
anchors {
bottom: parent.bottom
left: parent.left
right: parent.right
}
RowLayout {
id: rowLayout
anchors.fill: parent
anchors.margins: 10
Button {
text: "quit"
}
}
}
这可确保声明为 Footer
实例的子项的任何项目都将添加到其 RowLayout
.
This ensures that any items declared as children of Footer
instances will be added to its RowLayout
.
main.qml
:
import QtQuick 2.4
import QtQuick.Controls 1.3
ApplicationWindow {
width: 640
height: 480
visible: true
StackView {
id: stackView
anchors.fill: parent
initialItem: viewAComponent
}
Component {
id: viewAComponent
Rectangle {
id: viewA
color: "salmon"
Footer {
id: footerA
Button {
text: "Go to next view"
onClicked: stackView.push(viewBComponent)
}
}
}
}
Component {
id: viewBComponent
Rectangle {
id: viewB
color: "lightblue"
Footer {
id: footerB
Button {
text: "Go to previous view"
onClicked: stackView.pop()
}
}
}
}
}
我使用了 StackView
作为在视图之间导航的便捷方式.
I used StackView
as a convenient way of navigating between the views.
这篇关于将项目添加到自定义组件的布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!