我有一个 ListView 及其在其他 qml 文件中定义的委托(delegate)。
主.qml:
import QtQuick 2.12
import QtQuick.Window 2.12
Window {
visible: true
width: 640
height: 480
ListModel {
id: listModel
ListElement {
name: "Bill Smith"
}
ListElement {
name: "John Brown"
}
ListElement {
name: "Sam Wise"
}
}
ListView {
width: 180; height: 200
property color delegateColor: "green"
model: listModel
delegate: ExternalDelegate {}
}
}
外部委托(delegate).qml:
import QtQuick 2.12
import QtQuick.Controls 2.12
ItemDelegate {
background: Rectangle {
color: ListView.view.delegateColor
}
Text {
text: model.name
}
}
父级 ListView 有一个自定义属性 delegateColor。我需要从委托(delegate)中读取这个属性。但是,如果我尝试通过附加属性 ListView.view 访问它,它就不起作用。我在控制台中看到消息:
qrc:/ExternalDelegate.qml:7: TypeError: 无法读取 null 的属性“delegateColor”
如何从外部委托(delegate)读取 ListView 的自定义属性?
我需要在 ListView 中设置此属性(而不是在委托(delegate)中),因为我还想从页眉、页脚和部分委托(delegate)访问此属性。
最佳答案
在这种情况下,最好让组件不知道它们的用途,而是通过根元素的属性公开,例如可以创建矩形颜色的别名,在这种情况下ItemDelegate 组件已具有该属性的文本。
import QtQuick 2.12
import QtQuick.Controls 2.12
ItemDelegate {
id: root
property alias color: bg.color
background: Rectangle {
id: bg
}
contentItem: Text {
text: root.text
}
}
delegate: ExternalDelegate {
text: model.name
color: ListView.view.delegateColor
}
另一种解决方案是只更改新属性的别名:
import QtQuick 2.12
import QtQuick.Controls 2.12
ItemDelegate {
id: root
property color color : "white"
background: Rectangle {
color: root.color
}
contentItem: Text {
text: root.text
}
}
关于qt - 如何从外部委托(delegate)读取父 ListView 的自定义属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59852526/