布局项目
QML 提供了一种使用锚点(anchors)布局元素的灵活方式。锚点的概念是 Item 的基础,适用于所有可视 QML 元素。锚点就像一种契约,其优先级高于相互冲突的几何结构变化。锚点是相对关系的表达;你始终需要一个相关的元素来进行锚定。

一个元素有 6 条主要的锚点线( top 、 bottom 、 left 、 right 、 horizontalCenter 、 verticalCenter )。此外,对于 Text 元素中的文本,还有 baseline 锚点。每条锚点线都带有一个偏移量。对于 top 、 bottom 、 left 和 right 锚点,它们被称为边距(margins)。对于 horizontalCenter、 verticalCenter 和 baseline ,它们被称为偏移量(offsets)

- (1) 元素填充父元素。
GreenSquare {
BlueSquare {
width: 12
anchors.fill: parent
anchors.margins: 8
text: '(1)'
}
}
- (2) 元素与父元素左对齐。
GreenSquare {
BlueSquare {
width: 48
y: 8
anchors.left: parent.left
anchors.leftMargin: 8
text: '(2)'
}
}
- (3) 元素的左侧与父元素的右侧对齐。
GreenSquare {
BlueSquare {
width: 48
anchors.left: parent.right
text: '(3)'
}
}
- (4) 居中对齐的元素。
Blue1在父元素中水平居中。Blue2同样水平居中,但是相对于Blue1居中,且其顶部与Blue1的底线对齐。
GreenSquare {
BlueSquare {
id: blue1
width: 48; height: 24
y: 8
anchors.horizontalCenter: parent.horizontalCenter
}
BlueSquare {
id: blue2
width: 72; height: 24
anchors.top: blue1.bottom
anchors.topMargin: 4
anchors.horizontalCenter: blue1.horizontalCenter
text: '(4)'
}
}
- (5) 元素在父元素中居中
GreenSquare {
BlueSquare {
width: 48
anchors.centerIn: parent
text: '(5)'
}
}
- (6) 通过水平和垂直中心线,将元素定位在父元素的中心位置并带有左侧偏移
GreenSquare {
BlueSquare {
width: 48
anchors.horizontalCenter: parent.horizontalCenter
anchors.horizontalCenterOffset: -12
anchors.verticalCenter: parent.verticalCenter
text: '(6)'
}
}
方块经过了增强,是可以进行拖动的。请尝试运行示例并拖动其中的方块。你会发现:(1) 无法被拖动,因为它四周都被锚定了(不过你可以拖动 (1) 的父元素,因为父元素完全没有被锚定)。(2) 可以垂直拖动,因为只有左侧被锚定了。(3) 也是同理。(4) 只能垂直拖动,因为两个方块都在水平方向上居中对齐。(5) 在父元素中居中,因此无法被拖动。(6) 也是如此。拖动一个元素意味着改变它的 x,y 位置。由于锚定(anchoring)的优先级高于设置 x,y 属性,因此拖动会受到锚定线的限制。我们稍后在讨论动画时会再次看到这种效果。
2493



被折叠的 条评论
为什么被折叠?



