如何在QML中自动拉伸元素以使其所有子元素都适合它?以及如何指定间距?例如,我想在文本周围有一个矩形。矩形应该有一些内部空间。
如果我写下面的内容,则矩形的大小为0,0。
Rectangle {
color: "gray"
anchors.centerIn: parent;
Text {
text: "Hello"
}
}
如果我尝试按照 How to make QML items to grow to fit contents? 中的建议使用Column
元素进行修复,那么我会在整个窗口/父级中找到一列,
Column {
anchors.centerIn: parent
Rectangle {
color: "gray"
anchors.fill: parent
}
Text {
anchors.centerIn: parent
text: "Hello"
}
}
修改
我还尝试使用Flow
元素而不是Column
,但后来整个窗口/父级都有一行。
答案 0 :(得分:39)
您可以使用childrenRect
属性:
import QtQuick 1.1
Rectangle {
width: 320
height: 200
Rectangle {
color: "BurlyWood"
anchors.centerIn: parent
width: childrenRect.width + 20
height: childrenRect.height + 20
Text {
id: hello
x: 10
y: 10
text: "Hello"
}
Text {
anchors.left: hello.right
anchors.leftMargin: 10
anchors.top: hello.top
text: "World"
}
}
}
但是,请注意,在其中一个直接子项中使用childrenRect
并结合使用anchors.centerIn: parent
会产生有关绑定循环的警告。
答案 1 :(得分:7)
手动设置width
和height
有效,但有点难看:
Rectangle {
color: "gray"
width: label.width+20
height: label.height+20
anchors.centerIn: parent
Text {
id: label
anchors.centerIn: parent
text: "Hello"
}
}
答案 2 :(得分:0)
我认为使用 chilrenRect
属性是不够的(正如 Thorbjørn Lindeijer 所建议的那样)。它不会自动考虑子元素的所有不同边距。如果后者发生变化,根矩形不会自动调整其大小。我个人提出了以下解决方案:
Rectangle {
color: "white"
implicitWidth: row.implicitWidth + extraLeft + extraRight
implicitHeight: row.implicitHeight + extraTop + extraBottom
property int extraMargin: row.anchors.margins ? row.anchors.margins : 0
property int extraTop: row.anchors.topMargin ? row.anchors.topMargin : extraMargin
property int extraBottom: row.anchors.bottomMargin ? row.anchors.bottomMargin : extraMargin
property int extraLeft: row.anchors.leftMargin ? row.anchors.leftMargin : extraMargin
property int extraRight: row.anchors.rightMargin ? row.anchors.rightMargin : extraMargin
RowLayout {
id: row
spacing: 50
anchors.fill:parent
anchors.margins: 50
anchors.leftMargin: 100
Label {
text: "hello"
}
Label {
text: "world"
}
}
}