Bind to the listModel element of the QAbstractListModel class of an object in QML as Q_PROPERTY

I figured out how to set and associate an instance of the QAbstractListModel model with a derived list in / in QML.

But what I really want to do is expose the QML object and bind the element, which is the model deduced by QAbstractListModel, as Q_PROPERTY.

I tried it like this:

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 get a compilation error:

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

How to do it right?

+4
1

QObjects, QAbstractItemModels, , . Id :

Q_PROPERTY(MyListModel* myListModel READ myListModel CONSTANT)

, , myListModelChanged() CONSTANT.

, const:

MyListModel *MyObject::myListModel() const
+6

Source: https://habr.com/ru/post/1526884/


All Articles