How to access ListView's current item from qml

孤街醉人 提交于 2019-12-03 03:44:23
Richard1403832

This took me a very long time to find, as there are many incorrect solutions on Stackoverflow.

The pure QML way is to use a DelegateModel and access it from QML as follows:

import QtQuick 2.4
import QtQml.Models 2.1

ListView {
    property var currentSelectedItem

    onCurrentItemChanged{
            // Update the currently-selected item
            currentSelectedItem = myDelegateModel.items.get(currentIndex).model;
            // Log the Display Role
            console.log(currentSelectedItem.display);
    }

    model: DelegateModel {
        id: myDelegateModel
        model: myAbstractItemModel
        delegate: {
            // Define delegates here
        }
    }
}

This line returns an object (var) that you can access in the same way as within a delegate: myDelegateModel.items.get(currentIndex).model

This example assumes you are only using the default DelegateModelGroup.

See http://doc.qt.io/qt-5/qml-qtqml-models-delegatemodel.html and http://doc.qt.io/qt-5/qml-qtqml-models-delegatemodelgroup.html#get-method method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!