How do you access the roles of the currentItem from a listview in QML?

£可爱£侵袭症+ 提交于 2019-11-30 06:13:39

The code at http://comments.gmane.org/gmane.comp.lib.qt.qml/1778 should work, although I do see errors if the property is named 'data'; it looks like it is overriding some existing built-in property. Renaming it to 'myData' seems to work:

ListView {
    id: myId
    model: myModel
    delegate: Item {
        property variant myData: model
        Text {
            text: model.text
        }
        Text {
            text: model.moreText
        }    
    }
}

Text { text: myId.currentItem.myData.text }

(The myId.currentItem.text code in the original post didn't work because this was trying to refer to a text property within your delegate, which didn't exist.)

In regards to referring to model vs modelData within the delegate, the difference depends on the type of the model, rather than the number of roles in the model. If the model is a string list or object list, modelData is used to refer to the individual string or object from within a delegate (since string lists and object lists do not have any roles). For all other models, including the QML ListModel and the Qt C++ QAbstractItemModel, model.role can be used to refer to a role within a delegate.

You could alternatively access the model directly, with something like

Text { text: myModel[myId.currentIndex].text }

You can access a ListElement of ListModel using get() function.

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