我想将我的电话号码列表与左侧的一个字段(“名称”)和右侧的另一个字段(“电话”)对齐 . 但是,当尝试在委托中绑定锚属性时,它表示委托对象不是ListView组件的父对象 . 如何从代表处获取其他组件?
这是我的QML代码:
import QtQuick 2.7
import QtQuick.Controls 2.0
Item {
id: enclosing_area
width: 500
height: 300
ListModel {
id: dataModel
ListElement {
name: "John Smith"
phone: "1111-1111"
}
ListElement {
name: "Peter Poter"
phone: "2222-2222"
}
ListElement {
name: "Anna Lasalle"
phone: "3333-3333"
}
}
ListView {
id: list
width: enclosing_area.width
height: enclosing_area.height
model: dataModel
delegate: Rectangle {
width: enclosing_area.width
border.color: "red"
Label {
text: name
anchors.left: list.left
}
Label {
text: phone
anchors.right: list.right
}
}
}
}
qmlscene会产生以下错误:
file:///LViewTest.qml:36:13: QML Label: Cannot anchor to an item that isn't a parent or sibling.
file:///LViewTest.qml:32:13: QML Label: Cannot anchor to an item that isn't a parent or sibling.
file:///LViewTest.qml:36:13: QML Label: Cannot anchor to an item that isn't a parent or sibling.
file:///LViewTest.qml:32:13: QML Label: Cannot anchor to an item that isn't a parent or sibling.
file:///LViewTest.qml:36:13: QML Label: Cannot anchor to an item that isn't a parent or sibling.
file:///LViewTest.qml:32:13: QML Label: Cannot anchor to an item that isn't a parent or sibling.
第32和32行是“anchors.left”和“anchors.right”语句 . 在我的情况下,如何从委托中绑定到另一个对象中的属性?
2 回答
首先:
通常会调用你的
enclosing_area
root
.其次,如果您不想使用要锚定的对象的
id
,而是使用parent
.这可以防止您出现错误,因为 - 您正在尝试做的事情 - 不是锚定到
Label
的父级,而是锚定到它们的parent
sparent
.Label
的parent
将是delegate
中的Rectangle
.你为什么要选择锚定到
parent
而不是你的parent
id
?该对象将(几乎)始终具有可视父级,但此可视父级可能会更改 . 要么是因为你在代码中添加了一个额外的层,后来 - 甚至在运行时,通过重新创建它 . 所以你总是需要更新锚点 .
因此,锚定到
parent
可以解决一个简单的错误 .利用锚点而不是尝试硬编码子元素的大小以匹配其父元素 . 这将使您能够一直使用锚点 . (类似地,使用锚边距而不是硬编码的x,y值) . 你可以通过锚点获得很多其他好处 .