qt - 如何从外部委托(delegate)读取父 ListView 的自定义属性?

标签 qt listview qml qt5 qtquick2

我有一个 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/

相关文章:

c++ - Qt远程数据库与MySql?

android - 如何在 Android 的 ListView 中显示 YouTubePlayerView?

android - Listview 替换第一个项目而不是创建新项目

qt - 中心QML ListView高亮显示的项目

linux - qmake 在 linux 上使用不正确的 Qt 安装路径

C++/Qt - 无法从 qrc 文件打开 .txt

java - JVM初始化时出错

android - 在 ListView 中加载早期消息,如 whats app

qt - 如何在 BB 10 Cascades 中省略文本?

c++ - 发出 dataChanged 时,QML TreeView 项目不会更新