qt - 如何从外部委托读取父 ListView 的自定义属性?
问题描述
我有一个 ListView 及其在其他 qml 文件中定义的委托。
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"
}
ListElement {
name: "John Brown"
}
ListElement {
name: "Sam Wise"
}
}
ListView {
width: 180; height: 200
property color delegateColor: "green"
model: listModel
delegate: 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: Cannot read property 'delegateColor' of null
如何从外部委托读取 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
}
}
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
}
}
推荐阅读
- apache-flink - 表级别的 Flink TTL
- java - 使用 geckoddriver 时出错:发现意外的参数“--websocket-port”
- c - 如何将 char 缓冲区作为代码传递给 exec?
- conv-neural-network - 预测不在训练数据集中的类
- javascript - PUT XMLHttpRequest 在控制台返回空
- python - paramiko-sftp如何限制流量
- mql - 如何结合 Mongo $in 和 $cond
- css - 使用百分比将线性渐变应用于边框
- html - 如何在图像顶部对齐文本并使其具有响应性?
- javascript - 如何获取 Firebase 存储的图像 URL 的访问令牌?