qt - How to access ListView's current item from qml -


i have application stores , edits notes. list of notes displayed in listview this:

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 item notelistmodel subclasses qabstractlistmodel , contains notelistitems. store selected notelistitem access note object inside when user wants save modified note. however, don't know how access backing notelistitem qml delegate. modeldata seems else. there way so? if wrap note object in qvariant access through roles when tried 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();     } } 

it resulted in compiler error saying

qmetatype.h:642: error: invalid application of 'sizeof' incomplete type 'qstaticassertfailure'

or should try access selected list item backing code? there way that? dou have ideas?

thanks time. regards, peter

this took me long time find, there many incorrect solutions on stackoverflow.

the pure qml way use delegatemodel , access qml follows:

import qtquick 2.4 import qtqml.models 2.1  listview {     property var currentselecteditem      oncurrentitemchanged{             // update currently-selected item             currentselecteditem = mydelegatemodel.items.get(currentindex).model;             // log display role             console.log(currentselecteditem.display);     }      model: delegatemodel {         id: mydelegatemodel         model: myabstractitemmodel         delegate: {             // define delegates here         }     } } 

this line returns object (var) can access in same way within delegate: mydelegatemodel.items.get(currentindex).model

this example assumes using default delegatemodelgroup.

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


Comments