How to access the current ListView item from qml

I have an application that stores and edits notes. The list of notes is displayed as a list as follows:

Page { id: noteList title: i18n.tr("QNote") visible: false Column { anchors.fill: parent ListView { anchors.fill: parent model: notes delegate: ListItem.Standard { text: Title onClicked: editNote(NoteText, Title, modelData); progression: true } } } } function editNote(text, title, item) { pageStack.push(noteEdit, {title: title, text: text}); handler.setActiveItem(item); } 

The notes element is a NoteListModel that subclasses QAbstractListModel and contains NotesListItems. I would like to do this in order to save the currently selected NoteListItem so that I can easily access the Note object inside when the user wants to save the changed note. However, I do not know how to access backing NoteListItem from a qml delegate. modelData seems like something else. Is there any way to do this? If I could wrap the Note object in QVariant, I could easily access it through roles, but when I tried it like this,

 QVariant NoteListItem::data(int role) { switch (role) { case Title: return note.getTitle(); case NoteText: return note.getText(); case NoteObject: return QVariant::fromValue(note); default: return QVariant(); } } 

this led to a compiler error saying

qmetatype.h: 642: error: invalid application "sizeof" for the incomplete type "QStaticAssertFailure"

Or should I try to access the selected list item from the support code? Is there any way to do this? Do you have any ideas?

Thank you for your time. Regards, Peter

+4
source share
1 answer

It took me a lot of time since there are many wrong solutions in Stackoverflow.

A clean way of QML is to use the 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 the delegate: myDelegateModel.items.get(currentIndex).model

This example assumes that you are using only the delegate group 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

+5
source

Source: https://habr.com/ru/post/1479278/


All Articles