石家庄网站建设备案免费推广网站入口
在 QML 中,z
属性用于控制元素的堆叠顺序(Z 轴顺序),决定元素在视觉上的前后层次关系。
基本概念
-
默认行为:
-
所有元素的默认
z
值为 0 -
同层级元素后声明的会覆盖先声明的
-
父元素的
z
值会影响所有子元素
-
-
核心规则:
-
z
值越大,元素越靠前(越接近观察者) -
z
值可以是任意实数(包括负值) -
同一父元素下的子元素比较
z
值
-
基本用法
qml
import QtQuick 2.15Item {width: 300; height: 200// 红色矩形(默认 z=0)Rectangle {x: 50; y: 50width: 100; height: 100color: "red"}// 绿色矩形(覆盖红色)Rectangle {x: 80; y: 80width: 100; height: 100color: "green"}// 蓝色矩形(设置 z=1,显示在最前面)Rectangle {x: 110; y: 110width: 100; height: 100color: "blue"z: 1}
}
高级用法
1. 动态改变 z 值
qml
Rectangle {id: rectwidth: 100; height: 100color: "orange"MouseArea {anchors.fill: parentonClicked: rect.z += 1 // 每次点击提升层级}
}
2. 父元素 z 值影响
qml
Item {width: 300; height: 200// 父容器设置 z=1Item {z: 1Rectangle {x: 50; y: 50width: 100; height: 100color: "red"}}// 这个矩形即使 z=2 也会在红色矩形后面Rectangle {x: 80; y: 80width: 100; height: 100color: "green"z: 2}
}
3. 负 z 值使用
qml
Rectangle {width: 300; height: 200color: "lightgray"// 背景元素(负 z 值)Rectangle {anchors.fill: parentanchors.margins: 20color: "darkblue"z: -1}// 前景内容Text {text: "前景内容"anchors.centerIn: parentcolor: "white"font.pixelSize: 24}
}
实际应用场景
1. 弹出对话框
qml
Item {width: 400; height: 300// 主内容Rectangle {anchors.fill: parentcolor: "lightblue"}// 半透明遮罩层Rectangle {id: overlayanchors.fill: parentcolor: Qt.rgba(0,0,0,0.5)visible: falsez: 10}// 对话框(居中显示)Rectangle {id: dialogwidth: 200; height: 150anchors.centerIn: parentvisible: falsez: 11 // 比遮罩层高Button {text: "关闭"onClicked: {overlay.visible = falsedialog.visible = false}}}Button {text: "显示对话框"onClicked: {overlay.visible = truedialog.visible = true}}
}
2. 卡片堆叠效果
qml
Row {spacing: -50 // 卡片部分重叠Repeater {model: 5Rectangle {width: 100; height: 150radius: 5color: Qt.hsla(index/10, 0.5, 0.7, 1)border.color: "gray"z: index // 使卡片按顺序堆叠Text {text: index + 1anchors.centerIn: parentfont.pixelSize: 24}MouseArea {anchors.fill: parentonClicked: parent.z += 5 // 点击时提升层级}}}
}
注意事项
-
性能考虑:
-
频繁修改
z
值会导致重绘,影响性能 -
对于静态布局,应预先设置好
z
值
-
-
与 opacity 的关系:
-
即使设置
opacity: 0
,元素仍会参与层级排序 -
设置
visible: false
则完全从渲染树中移除
-
-
与父元素的关系:
-
子元素的
z
值只在父元素内部有效 -
父元素的
z
值决定了整个子树的位置
-
-
与 Loader 的交互:
-
Loader 加载的内容继承 Loader 的
z
值
-