Important: Please read the Qt Code of Conduct -

How to pass QAbstractListModel derived class to QML using setProperty?

  • Hello!

    On QML side I have an element, that contains a ListView plus some additional elements like scroll bars, control buttons etc.
    On C++ side I have a QObjectList of some items that I'm passing to my QML object using:
    QObject* qObject = myView->findObject<QObject*>("myObjectName");
    qObject->setProperty("myModel", QVariant::fromValue((QObjectList) *pointerToMyList);

    Now I need to change my QObjectList to QAbstractListModel derived class, but I cannot find a way to pass a pointer to QML using qObject->setProperty. All the examples I saw, use the setContextProperty. I want to avoid that, because the name of my qObject I am receiving via network and I can have many ListViews on a single page. So using my way, I'm just finding a correct QML object on the view and then change its model.

    So finally the question is: how can I pass the pointer (to the object of class derived from QAbstractListModel) to QML using qObject->setProperty method?

    Thanks in advance,

  • You need to register QAbstractItemModel as qml type in C++:

    From then on it should work.
    Make sure you declare the property like this:
    @Q_PROPERTY(QAbstractItemModel *myModel READ myModel NOTIFY modelChanged)@

  • Thank you!

    I just also needed to add

    @Q_DECLARE_METATYPE(CListModel* )@

    to .h file.

Log in to reply