5

我想出了如何在 QML 中公开和绑定 QAbstractListModel 派生列表模型的实例。

但我真正想做的是向 QML 公开一个对象并将一个 QAbstractListModel 派生列表模型的成员绑定为 Q_PROPERTY。

我试过这样:

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
    }
}

但我得到一个编译错误:

E:\Qt\Qt5\5.1.1\mingw48_32\include\QtCore\qglobal.h:946: 错误:'QAbstractListModel& QAbstractListModel::operator=(const QAbstractListModel&)' 是私有类 &operator=(const Class &) Q_DECL_EQ_DELETE; ^

正确的方法是如何做到这一点?

4

1 回答 1

8

QObjects 像 QAbstractItemModels 不能被复制,你必须使用一个指针。我会使用:

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
于 2014-02-14T07:44:15.633 回答