如何访问DelegateModel的委托中的section属性

问题描述 投票:0回答:1

请考虑以下代码:

import QtQuick 2.0
import QtQuick.Window 2.14
import QtQml.Models 2.2

Window {
    width: 200
    height: 100
    visible: true
    DelegateModel {
        id: visualModel
        model: ListModel {
            ListElement {
                name: "Apple"
            }
            ListElement {
                name: "Orange"
            }
        }
        delegate: Rectangle {
            height: 25
            width: 100
            Text {
                text: "Name: " + name + " Current section: <insert current section here>"  ; // How to get section here
            }
        }
    }

    ListView {
        anchors.fill: parent
        model: visualModel
        section.property: "name"
        section.criteria: ViewSection.FullString
        section.delegate: Text {
            text: section
        }
    }
}

这里,我需要从visualModel的委托中的ListView访问附加的节属性,但是我似乎无法获得它,我尝试了不同的组合,例如直接访问它或通过模型的属性,但是似乎无济于事,我们将不胜感激

qt model delegates qml
1个回答
0
投票

这可以使用https://doc.qt.io/qt-5/qtqml-syntax-objectattributes.html#a-note-about-accessing-attached-properties-and-signal-handlers完成

基本上,您必须使用此语法-><delegate root item>.ListView.section所以上面的工作代码看起来像这样

import QtQuick 2.0
import QtQuick.Window 2.14
import QtQml.Models 2.2

Window {
    width: 200
    height: 100
    visible: true
    DelegateModel {
        id: visualModel
        model: ListModel {
            ListElement {
                name: "Apple"
            }
            ListElement {
                name: "Orange"
            }
        }
        delegate: Rectangle {
            id: root
            height: 25
            width: 100
            Text {
                text: "Name: " + name + " Current section: " + root.ListView.section  ; 
            }
        }
    }

    ListView {
        anchors.fill: parent
        model: visualModel
        section.property: "name"
        section.criteria: ViewSection.FullString
        section.delegate: Text {
            text: section
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.