Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Bind a QAbstractListModel derived listmodel member of an object in QML as Q_PROPERTY

I figured out how to expose and bind an instance of a QAbstractListModel derived listmodel to/in QML.

But what I really want to do is to expose an object to QML and bind a member which is a QAbstractListModel derived listmodel as Q_PROPERTY.

I've tried it this way:

class MyObject : public QObject
    Q_PROPERTY(MyListModel myListModel READ myListModel NOTIFY myListModelChanged)

        explicit MyObject(QObject *parent = 0);
        MyListModel *myListModel();

        void myListModelChanged();

    public slots:

        MyListModel *m_myListModel;


MyObject::MyObject(QObject *parent) :
    m_myListModel = new MyListModel(this);

MyListModel *MyObject::myListModel()
    return m_myListModel;

class MyListModel : public QAbstractListModel {

int main(int argc, char *argv[])
    QGuiApplication a(argc, argv);

    QQuickView *view = new QQuickView();
    MyObject *myObject = new MyObject();

    view->engine()->rootContext()->setContextProperty("myObject", myObject);    

    return a.exec();

Rectangle {
    width: 200
    height: 200


    ListView {
        id: myListView
        anchors.fill: parent
        delegate: myDelegate
        model: myObject.myListModel

But I'm getting an compile error:

E:\Qt\Qt5\5.1.1\mingw48_32\include\QtCore\qglobal.h:946: error: 'QAbstractListModel& QAbstractListModel::operator=(const QAbstractListModel&)' is private Class &operator=(const Class &) Q_DECL_EQ_DELETE; ^

How is the right way to do this?

like image 361
avb Avatar asked Mar 20 '23 21:03


1 Answers

QObjects like QAbstractItemModels cannot be copied, you must use a pointer. I’d use:

Q_PROPERTY(MyListModel* myListModel READ myListModel CONSTANT)

As you don’t replace the model itself, just its content, you don’t need the myListModelChanged() signal and can mark it as CONSTANT.

Your getter already has the right type, although it should be const:

MyListModel *MyObject::myListModel() const
like image 152
Frank Osterfeld Avatar answered Apr 07 '23 02:04

Frank Osterfeld