Access Listview currentIndex from Delegate

前端 未结 2 1234
故里飘歌
故里飘歌 2021-02-03 15:07

I have a QML ListView where the delegate loads it\'s component from another file. When clicking on an delegate item, I want to update ListView. C

2条回答
  •  暖寄归人
    2021-02-03 15:38

    Use attached property ListView.view:

    This attached property holds the view that manages this delegate instance

    Small example:

    import QtQuick 2.4
    import QtQuick.Window 2.2
    import QtQuick.Layouts 1.1
    
    Window {
        width: 600
        height: 400
        visible: true
    
        Component {
            id: listDelegate
            Rectangle {
                height: 30
                width: parent.width
                color:  ListView.isCurrentItem ? "orange" : "white"
                property var view: ListView.view
                property int itemIndex: index
                Text { anchors.centerIn: parent; text: name }
                MouseArea {
                    anchors.fill: parent
                    onClicked: {
                        view.currentIndex = itemIndex;
                    }
                }
            }
        }
    
        RowLayout {
            anchors.fill: parent
            ListView {
                Layout.minimumWidth: parent.width / 2
                Layout.fillHeight: true
                model: ListModel {
                    ListElement {name: "item1.1"}
                    ListElement {name: "item1.2"}
                    ListElement {name: "item1.3"}
                }
                delegate: listDelegate
            }
            ListView {
                Layout.minimumWidth: parent.width / 2
                Layout.fillHeight: true
                model: ListModel {
                    ListElement {name: "item2.1"}
                    ListElement {name: "item2.2"}
                    ListElement {name: "item2.3"}
                }
                delegate: listDelegate
            }
        }
    }
    

提交回复
热议问题