Question

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?

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top