将整个QAbstractTableModel传递给QML

时间:2019-06-03 14:27:55

标签: c++ qt qml qabstracttablemodel

我将QAbstractTableModel子类化。现在,我想谈谈QML方面。我发现的所有示例都使用Q_INVOKABLE(即datasetData公开了类的重写方法。是否可以将整个QAbstractTableModel对象作为Q_INVOKABLE传递?如果是,该怎么做?

1 个答案:

答案 0 :(得分:2)

Q_INVOKABLE用于将QObject派生类型的方法公开给QML。您可以使用Qt property system从“全局对象”中公开QAbstractTableModel,该对象已通过QML上下文提供给QML(如您在问题中所评论)。

您可以从文档中进一步了解exposing Attributes of C++ Types to QML

源自QAbstractTableModel的MyTableModel:

class MyTableModel : public QAbstractTableModel
{
    Q_OBJECT
};

MyGlobalObject通过属性系统公开MyTableModel成员变量:

class MyGlobalObject : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QAbstractTableModel* myTableModel READ myTableModel CONSTANT)
public:
    MyGlobalObject(QObject *parent = nullptr) : QObject(parent), m_myTableModel(new MyTableModel) { }
    MyTableModel *myTableModel() { return m_myTableModel.data(); }
private:
    QScopedPointer<MyTableModel> m_myTableModel;
};

MyGlobalObject实例在main中设置为上下文属性

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;
    MyGlobalObject model;
    engine.rootContext()->setContextProperty("myGlobalObject", &model);
}

MyTableModel用作QML TableView的模型:

import QtQuick 2.12

TableView {
    model: myGlobalObject.myTableModel
}