How to expose QAbstractListModel derived model from QObject to QML?



  • I would like to know if there is any macro or way how to register Qt model as property of QObject for QML.

    For example, I have AnimalModel (http://doc.qt.io/qt-5/qtquick-modelviewsdata-cppmodels.html#qabstractitemmodel).

    I Know I can pass it to root context of QuickView

    QuickView view;
    view.rootContext()->setContextProperty("myModel", &model);
    

    In case I have QObject registered via Qml macros, I can pass this object to view too:

    view.rootContext()->setContextProperty("obj", pDataObject);
    

    But what If I want to have QObject which holds model of any data?

    For example:

    class DataObject : public QObject
    {
        Q_OBJECT
    
        Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged)
        Q_PROPERTY(QString color READ color WRITE setColor NOTIFY colorChanged)
        ...
    
        AnimalModel m_modelAnimals;
    
        //Is this possible in any way?
        //Q_PROPERTY(AnimalModel modelAnimals READ modelAnimals NOTIFY modelAnimalsChanged)
    };
    
    

    Every example I found until now shows how to pass QAbstractListModel to root context. But none how to use it as QObject property.

    (I know there is QQmlListProperty but QQmlListProperty doesn't support partial refresh. It's always necessary to rebuild all Qml objects)


  • Lifetime Qt Champion

    Hi,

    Yes you can, using e.g. a Q_INVOKABLE getter or creating a Q_PROPERTY for your model.



  • Thanks for reply. I already solved it too.

    It's necessary to return pointer to AnimalModel and not reference. Also there is no necessity for NOTIFY.

    So this is the correct way:

    Q_PROPERTY(AnimalModel * modelAnimals READ modelAnimals CONSTANT)
    AnimalModel* modelAnimals() { return &m_model;}

Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.