1、 应用场景
有时候需要模拟弹窗效果,需要下层的页面半透明显示。仅仅将上层页面背景设置为透明并不能实现这个效果,下层的页面依然被覆盖。Qt帮助文档中有如下代码,经测试有效果。
2、 代码
重点标记:
- 下层页面需要设置这个属性
StackView.visible: true
。 - 设置后有个问题:如果此页面有可点击的组件,被放到下层后依然可以被点击,这不是我们想要的。
- 解决思路是当页面被放入下层后用一个MouseArea覆盖。
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15Window {width: 1000height: 600visible: truetitle: qsTr("Hello World")Component {id: pageRectangle {property real pos: StackView.index * stackView.offsetproperty 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: _mMaskTouchanchors.fill: parentz: 99}onFocusChanged: {_mMaskTouch.enabled = !focus}}}StackView {id: stackViewproperty real offset: 10width: 100; height: 100initialItem:pagepushEnter: Transition {id: pushEnterParallelAnimation {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: popExitParallelAnimation {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: pushExitPropertyAction { property: "x"; value: pushExit.ViewTransition.item.pos }PropertyAction { property: "y"; value: pushExit.ViewTransition.item.pos }}popEnter: Transition {id: popEnterPropertyAction { property: "x"; value: popEnter.ViewTransition.item.pos }PropertyAction { property: "y"; value: popEnter.ViewTransition.item.pos }}}Button{text: "push"width: 100height: 100x: 300onClicked: {stackView.push(page)}}Button{text: "pop"width: 100height: 100x: 300y: 200onClicked: {stackView.pop()}}
}