首页 > 解决方案 > 如何从外部委托读取父 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 中设置此属性(而不是在委托中),因为我还想从页眉、页脚和部分委托中访问此属性。

标签: qtlistviewqmlqt5qtquick2

解决方案


在这种情况下,最好让组件不知道它们的用途,而是通过根元素的属性来公开,例如可以创建矩形颜色的别名,在文本的情况下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
    }
}

推荐阅读