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