将背景设置为qml项目的最简单方法是只有一个子矩形,其锚点完全填满父项:
Item
{
width: 320
height: 240
Rectangle
{
id: background
anchors.fill: parent
color: "blue"
}
// other items
}
但是,这仅适用于父项具有定义的大小(宽度和高度) .
我想有一个没有为它定义固定大小的容器 . 孩子们将有固定的大小,但是当孩子们可以动态地改变他们的大小时,我希望父容器能够成长和缩小以适应 .
如果我按顺序锚定孩子,除了背景之外,一切都很好 .
关于类似的主题有a question a while ago,但问题是所有的孩子都是重叠而不是并排显示 . 这不是我的问题,因为将它们锚定在序列中(或使用 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
}
}
但是,不显示背景,因为父级没有定义的大小,尽管所有子级都有固定的大小,如果我指定最后一个子级的右锚作为父级的权限,它仍然是显示正确 . 我想这意味着渲染器应该知道父级的大小 .
(如果我使用 Item
或 Rectangle
而不是 RowLayout
,则没有任何变化 . 实际上,当使用 RowLayout
时我可以省略顺序锚定,但这不会改变我的背景问题)
1 回答
首先,如果您希望容器具有背景,则必须将
Rectangle
设为根,而不是将Rectangle
放在Item
中 . 此外,您不能在Layout
中使用锚点,因为Layout
根据自己的规则管理其子项的布局 .至于这个问题,你可以使用
Layout
,因为它增长到包含它的所有子节点,如下面的代码所示:另一个解决方案是使用
Item.childrenRect
: