gpt4 book ai didi

qml - 如何为未指定大小的 qml 项设置背景?

转载 作者:行者123 更新时间:2023-12-04 16:31:20 33 4
gpt4 key购买 nike

为 qml 项设置背景的最简单方法是让子矩形的 anchor 完全填满父项:

Item
{
width: 320
height: 240
Rectangle
{
id: background
anchors.fill: parent
color: "blue"
}

// other items

}

但是,这只适用于父项定义了大小(宽度和高度)。

我想要一个容器,但没有为其定义固定大小。 children 将有固定的尺寸,但由于 children 可以动态改变他们的尺寸,我希望父容器能够增长和缩小以适应。

如果我按顺序 anchor 定 child ,除了背景之外,一切都很好。

a question a while ago关于一个类似的主题,但问题是所有 child 都重叠而不是并排显示。这不是我的问题,因为将它们按顺序 anchor 定(或使用 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

}

}

但是,由于父级没有定义大小,所以没有显示背景,尽管所有子级都有固定大小,如果我指定最后一个子级的右 anchor 为父级的右侧,它仍然是正确显示。我想这意味着渲染器应该知道父级的大小。

(如果我使用 ItemRectangle 而不是 RowLayout ,没有任何变化。实际上,当使用 RowLayout 我可以省略顺序 anchor 定,但这不会改变我的背景问题)

最佳答案

首先,如果你想让你的容器有背景,你必须制作Rectangle根而不是放置 RectangleItem .此外,您不能在 Layout 中使用 anchor 。自 Layout根据自己的规则管理其子项的布局。

至于问题,你可以用Layout因为它增长到包含它的所有 child ,就像在下面的代码中一样:

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"
}
}
}
}

另一种解决方案是使用 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)
}
}
}

关于qml - 如何为未指定大小的 qml 项设置背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36175101/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com