qml 中的anchors
理解 QML 中的 anchors(锚定)
在 QML 中,anchors
是一种强大的布局机制,用于相对于父元素或同级元素定位和调整组件大小。它比简单的 x/y 坐标定位更灵活,能够自动适应不同屏幕尺寸。
基本概念
在你的代码中,anchors
出现在两个地方:
Grid {
anchors.fill: parent
anchors.margins: 8
// ...
}
1. anchors.fill: parent
- 这表示 Grid 元素将填充其父元素(在这里是 DarkSquare)的整个可用空间
- 相当于同时设置了:
anchors.left: parent.left
anchors.right: parent.right
anchors.top: parent.top
anchors.bottom: parent.bottom
2. anchors.margins: 8
- 这为所有四个边(上、下、左、右)设置统一的边距为 8 像素
- 也可以单独设置:
anchors.leftMargin: 8 anchors.rightMargin: 8 anchors.topMargin: 8 anchors.bottomMargin: 8
常用锚定属性
-
基本锚定:
anchors.left
: 左边缘锚定anchors.right
: 右边缘锚定anchors.top
: 顶部锚定anchors.bottom
: 底部锚定anchors.horizontalCenter
: 水平中心锚定anchors.verticalCenter
: 垂直中心锚定
-
边距:
anchors.margins
: 所有边距anchors.leftMargin
等: 特定边距
-
居中:
anchors.centerIn
: 在另一个元素中居中
-
填充:
anchors.fill
: 填充另一个元素
使用注意事项
- 每个元素只能锚定到一个元素(通常是父元素或同级元素)
- 避免锚定循环(A 锚定到 B,B 又锚定到 A)
- 不能混合绝对定位(x,y)和锚定
- 锚定比手动设置 x,y,width,height 更灵活,能自动适应不同屏幕尺寸
在你的代码中,使用 anchors.fill: parent
确保 Grid 填满整个 DarkSquare(留有 8 像素边距),然后 Grid 内部使用 spacing 属性来控制单元格之间的间距。