QML AbstractItemModel access by Row and Role
I have a C++ model based on QAbstractItemModel
I know the Parent ModelIndex, Row Number and the Role Name of the data I wish to access.
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?
Have a look in <QtInstall>\Src\qtquick1\src\declarative\graphicsitems
You can do something like this explained here.
Also starting from
Qt 5.5following works somehow (since I don't know the reason yet).
myModelis a C++
QAbstractItemModelderived 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
Now trying to find out how to get the role outside
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.
Thanks, I hadn't thought of doing it that way.
In Qt 5.4 you can do this if you set Q_INVOKABLE on
QAbstractItemModel::index(int row, int column, const QModelIndex &parent)and
QAbstractItemModel::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 a
VisualDataModelin the documentation), as the
DelegateModelGroupwithin that has a
get(row)function that returns an Object through which you can access the data in the same way as in a QML Delegate.
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:
DelegateModelobject (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.
myDelegateModel.rootIndexto 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.