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_OBJECT
    Q_PROPERTY(MyListModel myListModel READ myListModel NOTIFY myListModelChanged)

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

    signals:
        void myListModelChanged();

    public slots:

    private:
        MyListModel *m_myListModel;

};


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

MyListModel *MyObject::myListModel()
{
    return m_myListModel;
}

class MyListModel : public QAbstractListModel {
    Q_OBJECT
//...   
//...
}

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

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

    view->engine()->rootContext()->setContextProperty("myObject", myObject);    
    view->setSource(QUrl::fromLocalFile("main.qml"));   
    view->show();

    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 14:03

avb


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 06 '23 19:04

Frank Osterfeld