我有一个 ColumnLayout
,其 anchor 设置为 anchor.fill: parent
,因此它已经有一个集合维度,这取决于它的父维度。
如何添加 Rectangles
进入此 ColumnLayout
,从上到下有特定的间距?
现在我有这个:
ColumnLayout {
anchors.fill: parent
spacing: 2
Rectangle {
height: 50
width: 50
color: "red"
}
Rectangle {
height: 50
width: 50
color: "green"
}
Rectangle {
height: 50
width: 50
color: "blue"
}
}
但不是让矩形从上到下有间距
2
它布局 Rectangle
s 均匀地在 ColumnLayout
.一种解决方案是将第一个矩形 anchor 定到父级的顶部,并将其余矩形一个接一个地 anchor 定,但如果可能,我想避免这种情况。
最佳答案
与以前的定位器不同,例如 Column
或 Row
, 布局被引入以支持 UI 的图形缩放,也是由 引入的。灌装可用空间(在这种特定情况下填充其父级)。在这个意义上,spacing
属性不应被视为 Item
之间间距的严格上限s 但作为 最小允许距离 它们之间。
当前解决您的问题的方法是使用“填充物”Item
,它使用 fillHeight
属性(property)。此 Item
占据了对方留下的所有空间Item
s 在布局中,因此根据需要将它们打包在一起:
import QtQuick 2.5
import QtQuick.Window 2.2
Window {
visible: true
width: 100
height: 200
ColumnLayout {
anchors.fill: parent
spacing: 2
Rectangle {
height: 50
width: 50
color: "red"
}
Rectangle {
height: 50
width: 50
color: "green"
}
Rectangle {
height: 50
width: 50
color: "blue"
}
Item { Layout.fillHeight: true } // <-- filler here
}
}
请注意,您可以利用相同的方法并在布局的开头添加一个填充符以垂直居中子项
Item
s。最后,请注意,在这种情况下,建议使用 Column
其中放置了 Item
s 如预期正确,不考虑剩余的可用空间。只要做出你的选择。
应该注意的是,虽然这种方法有效
Layout
s 提供了很多属性来控制Item
的大小s。请引用other answer对这个主题的一些见解。
关于qt - 如何为 QML 布局中的项目提供特定间距?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35587755/