QML AbstractItemModel access by Row and Role
-
I have a C++ model based on QAbstractItemModel
I need to access the data from QML JavaScript.
I know the Parent ModelIndex, Row Number and the Role Name of the data I wish to access.How do I access the actual data using Javascript within QML?
Every hint I can find involves rewriting the model to add either specific invokable getters, or an invokable get() method that returns an object representing the entire row. This feels completely wrong in every way, and cannot be the only option.
Delegates clearly do this. How do they do this?
-
The ListView is a cpp class which knows how to get the data from the model. No javascript involved. If you want to get data from the model in javascript you need to expose it yourself.
Have a look in <QtInstall>\Src\qtquick1\src\declarative\graphicsitems
-
Hi @Richard15,
You can do something like this explained here.
Also starting fromQt 5.5
following works somehow (since I don't know the reason yet).
AssumingmyModel
is a C++QAbstractItemModel
derived model set as a context property, then in QML :console.log(myModel.data(myModel.index(0,0),258)) //where //(0,0) = row and column //258 = the role enum number, you can get these from C++
This works outside of
ListView
too.
Now trying to find out how to get the role outsideListView
-
@t3685
As stated in the OP, I know I can write specific getter/setter methods into my QAbstractItemModel subclasses.
However, if that really was the only option then QML would be effectively useless for nontrivial data-driven applications as the data models cease to be a standard interface.@p3c0
Thanks, I hadn't thought of doing it that way.
In Qt 5.4 you can do this if you set Q_INVOKABLE onQAbstractItemModel::index(int row, int column, const QModelIndex &parent)
andQAbstractItemModel::data(const QModelIndex &index, int role)
methods.
I'm guessing this has been done for you in Qt 5.5.I have also found that in Qt 5.4 (and presumably 5.5) it's also possible to get there via a
DelegateModel
(often called aVisualDataModel
in the documentation), as theDelegateModelGroup
within that has aget(row)
function that returns an Object through which you can access the data in the same way as in a QML Delegate.
http://doc.qt.io/qt-5.4/qml-qtqml-models-delegatemodelgroup.html#get-method
However, I haven't yet figured out when it reads the data from the underlying model.Thus, if the DelegateModel has only the default DelegateModelGroup:
myDelegateModel.items.get(%row%).model.%role_name%
In this,
myDelegateModel
is aDelegateModel
object (which may also be used as the model in a ListView, GridView or PathView),%row%
is the row number and%role_name%
is the role.
SetmyDelegateModel.rootIndex
to the appropriate parent QModelIndex.PS: $Deity the documentation is beyond awful. So many links straight back to exactly where you are masquerading as a link to what the thing is.