QML 矩形:检测到属性"width"/"height"的绑定循环



我正在尝试将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)。在大多数情况下,您需要parentwidth和固定(或在极少数情况下动态)height。看看这个例子 - 我用anchors来调整宽度和固定height80:

anchors {
left: parent.left
right: parent.right
}
height: 80

您可能还对Label此组件内的定位感兴趣。

最新更新