⚠️ Forum Maintenance: Feb 6th, 8am - 14pm (UTC+2)

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?

  • @Richard15

    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

  • Moderators

    Hi @Richard15,
    You can do something like this explained here.
    Also starting from Qt 5.5 following works somehow (since I don't know the reason yet).
    Assuming myModel is a C++ QAbstractItemModel derived model set as a context property, then in QML :

    //(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 outside ListView

  • @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.

    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 VisualDataModel in the documentation), as the DelegateModelGroup within 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:


    In this, myDelegateModel is a DelegateModel 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.
    Set myDelegateModel.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.

Log in to reply