我遇到了这个:
ListView {
id: listView
model: ["Lorem","Ipsum"]
delegate: Item {
height: 20
Text {
z: 2
text: modelData
anchors.fill: parent
}
Rectangle {
z: 1
color: "red"
// this does not work:
anchors.fill: parent
// this works, but I have mixed feelings about it:
// height: 20; width: listView.width
}
}
}
所以,显然,anchors
在一个委托的子项中不起作用(在这种情况下,Rectangle
根本不显示)。我想了解这背后的机制。另外,我想问一下,处理这种情况的首选方法是什么?谢谢你!
Item
的implicitWidth
和implicitHeight
为零,因此让Rectangle
和Text
填充它将导致它们也没有大小。
你的代码有两个问题:
-
ListView
没有指定width
或height
。 - 您的委托没有指定
width
。
这里有一种正确的方法:
import QtQuick 2.0
import QtQuick.Window 2.0
Window {
width: 300
height: 300
visible: true
ListView {
id: listView
anchors.fill: parent
model: ["Lorem","Ipsum"]
delegate: Item {
width: listView.width
height: textItem.implicitHeight
Text {
id: textItem
z: 2
text: modelData
width: parent.width
}
Rectangle {
z: 1
color: "red"
anchors.fill: parent
}
}
}
}
ListView
的文档有更多的信息