1、 应用场景
有时候需要模拟弹窗效果,需要下层的页面半透明显示。仅仅将上层页面背景设置为透明并不能实现这个效果,下层的页面依然被覆盖。Qt帮助文档中有如下代码,经测试有效果。
2、 代码
重点标记:
- 下层页面需要设置这个属性
StackView.visible: true
。 - 设置后有个问题:如果此页面有可点击的组件,被放到下层后依然可以被点击,这不是我们想要的。
- 解决思路是当页面被放入下层后用一个MouseArea覆盖。
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15
Window {
width: 1000
height: 600
visible: true
title: qsTr("Hello World")
Component {
id: page
Rectangle {
property real pos: StackView.index * stackView.offset
property real hue: Math.random()
color: Qt.hsla(hue, 0.5, 0.8, 0.6)
border.color: Qt.hsla(hue, 0.5, 0.5, 0.9)
StackView.visible: true //重点
Text{
text: stackView.depth
}
//防止在下层时被点击
MouseArea{
id: _mMaskTouch
anchors.fill: parent
z: 99
}
onFocusChanged: {
_mMaskTouch.enabled = !focus
}
}
}
StackView {
id: stackView
property real offset: 10
width: 100; height: 100
initialItem:page
pushEnter: Transition {
id: pushEnter
ParallelAnimation {
PropertyAction { property: "x"; value: pushEnter.ViewTransition.item.pos }
NumberAnimation { properties: "y"; from: pushEnter.ViewTransition.item.pos + stackView.offset; to: pushEnter.ViewTransition.item.pos; duration: 400; easing.type: Easing.OutCubic }
NumberAnimation { property: "opacity"; from: 0; to: 1; duration: 400; easing.type: Easing.OutCubic }
}
}
popExit: Transition {
id: popExit
ParallelAnimation {
PropertyAction { property: "x"; value: popExit.ViewTransition.item.pos }
NumberAnimation { properties: "y"; from: popExit.ViewTransition.item.pos; to: popExit.ViewTransition.item.pos + stackView.offset; duration: 400; easing.type: Easing.OutCubic }
NumberAnimation { property: "opacity"; from: 1; to: 0; duration: 400; easing.type: Easing.OutCubic }
}
}
pushExit: Transition {
id: pushExit
PropertyAction { property: "x"; value: pushExit.ViewTransition.item.pos }
PropertyAction { property: "y"; value: pushExit.ViewTransition.item.pos }
}
popEnter: Transition {
id: popEnter
PropertyAction { property: "x"; value: popEnter.ViewTransition.item.pos }
PropertyAction { property: "y"; value: popEnter.ViewTransition.item.pos }
}
}
Button{
text: "push"
width: 100
height: 100
x: 300
onClicked: {
stackView.push(page)
}
}
Button{
text: "pop"
width: 100
height: 100
x: 300
y: 200
onClicked: {
stackView.pop()
}
}
}