堆叠式界面的实现的核心组件就是StackView。StackView是一个基于栈的导航浏览模型,可以与一组关联的页面一起使用。当用户浏览深层页面时,深层页面被推到栈顶,当用户选择返回时,之前浏览的页面会再次弹出。
堆叠式界面的效果
上述演示中,界面一共有四个:分别是home、profile、about和editprofile
上述四个界面中使用的核心组件是Page,该组件在QtQuick.Controls中,Page是一个容器控件,可以方便地添加页眉、页脚以及其他item。page的结构如下
上述四个界面的实现如下
Home.qml
import QtQuick 2.6
import QtQuick.Controls 2.5
Page {
title: qsTr("Home")
Label {
anchors.centerIn: parent
text: qsTr("Home Screen")
}
}
Profile.qml
import QtQuick 2.0
import QtQuick.Controls 2.5
Page {
title: qsTr("Profile")
Column {
anchors.centerIn: parent
spacing: 10
Label {
text: qsTr("Profile page")
anchors.horizontalCenter: parent.horizontalCenter
}
Button {
text: qsTr("Edit")
anchors.horizontalCenter: parent.horizontalCenter
onClicked: {
stackview.push("EditProfile.qml")
}
}
}
}
About.qml
import QtQuick 2.6
import QtQuick.Controls 2.5
Page {
title: qsTr("About")
Label {
text: qsTr("About page")
anchors.centerIn: parent
}
}
EditProfile.qml
import QtQuick 2.6
import QtQuick.Controls 2.5
Page {
title: qsTr("EditProfile")
Label {
text: qsTr("edit profile")
anchors.centerIn: parent
}
}
上述四个界面实现完之后,就是如何用StackView组件将四个界面串起来,具体代码如下
import QtQuick 2.14
import QtQuick.Window 2.14
import QtQuick.Controls 2.5
ApplicationWindow {
id:root
visible: true
height: 480
width: 640
header: ToolBar {
ToolButton {
id:toolbtn
text: stackview.depth>1?"\u25C0" : "\u2630"
//button的图标是根据stackview的层级来决定显示哪个,而且,内容是有Unicode吗组成,\u2630是三个横线,而\u25C0是三角号
//depth表示的是stackview中item的数目
onClicked: {
if (stackview.depth>1) {//当depth大于1时,表示已经进入了深层的界面中,所以此时的toolbutton的图标是三角号,所以此时要执行pop
stackview.pop()//将一个或多个元素从栈顶移除,从而达到界面回退的效果
}
else {
drawer.open()//打开draw组件
}
}
}
Label {
text: stackview.currentItem.title//显示栈顶item的title
anchors.centerIn: parent
}
}
Drawer {//Drawer提供了一个基于滑动的侧面板,以提供导航界面的标题。
id:drawer
width: root.width*0.6
height: root.height
Column {
anchors.fill: parent
ItemDelegate {//ItemDelegate显示标准视图项。ItemDelegate相当于一个图形界面的代理,当点击ItemDelegate时,才会真正的显示图形界面,这里是将Profile放于stackview的顶部显示
text: qsTr("Profile")
width: parent.width
onClicked: {
stackview.push("Profile.qml")//点击Profile时,将组件Profile压栈,呈现出画面前进的效果
drawer.close()
}
}
ItemDelegate {
text: qsTr("About")
width: parent.width
onClicked: {
stackview.push(aboutpage)
drawer.close()
}
}
}
}
StackView {
id:stackview
anchors.fill: parent
initialItem: Home {//指定初始界面。此时depth的值为1
}
}
Component {//about组件
id:aboutpage
About {
}
}
}
其中,StackView中的initialItem属性指定了初始界面是Home,Component就是个组件元素,用来封装QML类型。
然后看一下ApplicationWindow的header属性,header是个ToolBar,在这个ToolBar中,有个ToolButton,button的图标是根据stackview的层级来决定显示哪个,而且,内容是有Unicode吗组成,\u2630是三个横线,而\u25C0是三角号
Drawer提供了一个基于滑动的侧面板,以提供导航界面的标题。
参考
《qml book》
欢迎大家评论交流,作者水平有限,如有错误,欢迎指出