我正在尝试将Rectangle
的大小调整为其内容的大小:
ListView {
anchors.fill: parent
model: ["a", "b", "c"]
delegate: Rectangle {
color: "gray"
property int margin: 20
width: childrenRect.width + 2 * margin
height: childrenRect.height + 2 * margin
Text {
text: modelData
anchors.centerIn: parent
}
}
}
它似乎在视觉上工作,但 QML 引擎给出了很多以下错误:
qrc:/main.qml:13:19:QML 矩形:检测到属性"宽度"的绑定循环
qrc:/main.qml:13:19:QML 矩形:检测到属性"高度"的绑定循环
绑定循环在哪里以及如何修复它?
错误来自项目Rectangle
:其大小基于其内容(通过使用childrenRect
)。但是,您的Text
是根据其父级的大小放置的(通过使用centerIn
)。
Text
的位置基于其父级的大小(以Rectangle
为中心)。childrenRect
保存子项的集合几何图形(例如边界矩形属性)。调整Rectangle
大小时,Text
的位置也会更改。然后,childrenRect
也将更改以映射Text
的新位置。
因此,如果在子 rect 属性上映射Rectangle
的大小并将Text
居中Rectangle
,则将创建一个循环。
向列表视图中居中的文本添加背景的快速示例:
ListView {
id: list
anchors.fill: parent
model: ["a", "b", "c"]
delegate: Item {
property int margin: 20
anchors.left: parent.left // Take all the width
anchors.right: parent.right
height: 40 // The height is 0 by default
Rectangle { // Background under the text only. Will not fill the whole row
color: "gray"
anchors.centerIn: parent
width: text.width
height: text.height
}
Text {
id: text
text: modelData
anchors.centerIn: parent
}
}
}
通常不常将delegate
的宽度绑定到其内容(childrenRect
)。在大多数情况下,您需要parent
的width
和固定(或在极少数情况下动态)height
。看看这个例子 - 我用anchors
来调整宽度和固定height
80:
anchors {
left: parent.left
right: parent.right
}
height: 80
您可能还对Label
此组件内的定位感兴趣。