为 qml 项设置背景的最简单方法是让子矩形的锚点完全填满父项:
Item
{
width: 320
height: 240
Rectangle
{
id: background
anchors.fill: parent
color: "blue"
}
// other items
}
Run Code Online (Sandbox Code Playgroud)
但是,这只适用于父项定义了大小(宽度和高度)。
我想要一个容器,但没有为其定义固定大小。孩子们将有固定的尺寸,但由于孩子们可以动态改变他们的尺寸,我希望父容器能够增长和缩小以适应。
如果我按顺序锚定孩子,除了背景之外,一切都很好。
有一个问题,前一阵子关于类似的话题,但问题是,所有的孩子们并排而不是重叠显示的一面。这不是我的问题,因为按顺序锚定它们(或使用 a RowLayout)可以正确显示它们。
Item
{
// I don't want a fixed size here
Rectangle
{
id: background
anchors.fill: parent
color: "blue"
}
RowLayout
{
anchors.fill: parent
Item
{
id: child1
anchors.left = parent.left
anchors.top: parent.top
width:100
height:100
}
Item
{
id: child2
anchors.left = child1.right
anchors.top: parent.top
width:120
height:120
}
// further children
}
}
Run Code Online (Sandbox Code Playgroud)
但是,由于父级没有定义大小,所以没有显示背景,尽管所有子级都有固定大小,如果我指定最后一个子级的右锚点为父级的右侧,它仍然是正确显示。我想这意味着渲染器应该知道父级的大小。
(如果我使用 anItem或 aRectangle而不是 ,则RowLayout没有任何变化。实际上,当使用 a 时,RowLayout我可以省略顺序锚定,但这不会改变我的背景问题)
首先,如果你想让你的容器有背景,你必须制作Rectangle根而不是放在Rectangle里面Item。此外,您不能在 a 中使用锚点,Layout因为 aLayout根据自己的规则管理其子项的布局。
至于问题,您可以使用 aLayout因为它增长到包含其所有子项,如下面的代码所示:
Rectangle {
anchors.centerIn: parent
width: grid.width + 10
height: grid.height + 10
color: "orange"
GridLayout {
anchors.centerIn: parent
id: grid
columns: 5
rowSpacing: 2
columnSpacing: 2
Repeater {
model: 10 + Math.round(Math.random() * 50)
Rectangle {
width: 20 + Math.round(Math.random() * 50)
height: 20 + Math.round(Math.random() * 50)
border.width: 1
border.color: "#999"
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
另一种解决方案是使用Item.childrenRect:
Rectangle {
id: container
anchors.centerIn: parent
width: childrenRect.x + childrenRect.width;
height: childrenRect.y + childrenRect.height;
border.width: 1
border.color: "#999"
Repeater {
model: 10 + Math.round(Math.random() * 50)
Rectangle {
x: Math.round(Math.random() * 500)
y: Math.round(Math.random() * 500)
width: 100 + Math.round(Math.random() * 100)
height: 100 + Math.round(Math.random() * 100)
color: Qt.rgba(Math.random(),Math.random(),Math.random(),1)
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15091 次 |
| 最近记录: |