Qt 如何从外部委托读取父ListView的自定义属性?
我在其他qml文件中定义了一个ListView及其委托 main.qml:Qt 如何从外部委托读取父ListView的自定义属性?,qt,listview,qml,qt5,qtquick2,Qt,Listview,Qml,Qt5,Qtquick2,我在其他qml文件中定义了一个ListView及其委托 main.qml: import QtQuick 2.12 import QtQuick.Window 2.12 Window { visible: true width: 640 height: 480 ListModel { id: listModel ListElement { name: "Bill Smith" }
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 {}
}
}
ExternalDelegate.qml:
import QtQuick 2.12
import QtQuick.Controls 2.12
ItemDelegate {
background: Rectangle {
color: ListView.view.delegateColor
}
Text {
text: model.name
}
}
父ListView具有自定义属性delegateColor。我需要从委托读取此属性。但是,如果我试图通过附加属性ListView.view访问它,它将不起作用。我在控制台中看到消息:
qrc:/ExternalDelegate.qml:7:TypeError:无法读取null的属性“delegateColor”
如何从外部委托读取ListView的自定义属性
我需要在ListView中设置此属性(不在委托中),因为我还希望从页眉、页脚和节委托访问此属性。在这种情况下,组件最好不知道它们用于什么,而是通过根元素的属性公开,例如,可以创建矩形颜色的别名,对于文本,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
}
}
另一种解决方案是仅更改新属性的别名:
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
}
}
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
}
}