ToolBar主要用于应用程序的上下文控制,就像导航按钮和搜索按钮那样。ToolBar就像窗口程序的header或footer那样。
ToolBar不提供自己的布局,不过需要开发者设置内容,如创建一个RowLayout。但设置了一个item在ToolBar上时,ToolBar会自己适应这个item的大小。
下面是官方的截图:
代码如下:
ApplicationWindow {
visible:true
header: ToolBar {
RowLayout {
anchors.fill: parent
ToolButton {
text: qsTr("‹")
onClicked: stack.pop()
}
Label {
text: "Title"
elide: Label.ElideRight
horizontalAlignment: Qt.AlignHCenter
verticalAlignment: Qt.AlignVCenter
Layout.fillWidth: true
}
ToolButton {
text: qsTr("⋮")
onClicked: menu.open()
}
}
}
StackView {
id: stack
anchors.fill: parent
}
}
这里提供下本人的例子,如下:
这里主要的代码如下:
header: ToolBar{
background: Rectangle {
color: "green"
}
RowLayout {
spacing: 20
anchors.fill: parent
ToolButton{
contentItem: Image{
fillMode: Image.Pad
horizontalAlignment: Image.AlignHCenter
verticalAlignment: Image.AlignVCenter
source: stackView.depth > 1 ? "images/back.png" : "images/drawer.png"
}
onClicked: {
if(stackView.depth > 1){
stackView.pop()
listView.currentIndex = -1
}
else{
drawer.open()
}
}
}
}
}
通过background:Rectangle去设置背景。
在ToolBar内部添加一个RowLayout。内部添加一个ToolButton,当stackView.depth > 1的时候,图标变成这样:
当回到主页后:
其中statckview和frawer代码如下:
Drawer {
id: drawer
width: Math.min(window.width, window.height) / 3
height: window.height
dragMargin: stackView.depth > 1 ? 0 : undefined
ListView {
id: listView
focus: true
currentIndex: -1
anchors.fill: parent
delegate: ItemDelegate {
width: parent.width
text: model.title
highlighted: ListView.isCurrentItem
onClicked: {
listView.currentIndex = index
stackView.push(model.source)
drawer.close()
}
}
model: ListModel {
ListElement {
title: "XXXXXX"
source: "qrc:/page/XXXXXX.qml"
}
ListElement {
title: "XXXXXX"
}
ListElement {
title: "XXXXXX"
}
ListElement {
title: "XXXXXX"
}
ListElement {
title: "XXXXXX"
}
ListElement {
title: "XXXXXX"
}
ListElement {
title: "XXXXXX"
}
ListElement {
title: "XXXXXX"
}
ListElement {
title: "XXXXXX"
}
}
}
}
其中是这样的效果: