How to expose a C++ Model to QML

余生长醉 提交于 2021-01-20 19:51:41

问题


I'm writing a QML+Qt application . I defined a class like this :

class MainClass : public QObject
{
    Q_OBJECT

public:
    rosterItemModel m_rosterItemModel;
.
.
.
}

rosterItemModel model is a class derived from QAbstractListModel. I exposed MainClass to qml part using this function :

qmlRegisterType<MainClass>("CPPIntegrate", 1, 0, "MainClass");

Now I want to assign this model(m_rosterItemModel) from MainClass to model property of a ListView in QML. I tried the following ways but none of them were helpful :(

  • I tried to declare m_rosterItemModel as a PROPERTY using Q_PROPERTY . I couldn't do that because it said that QAbstractListModel is not copy-able.
  • I tried to get a pointer to m_rosterItemModel in qml file using a Q_INVOKABLE function in MainClass. But it wasn't helpful too.

Could someone help me?


回答1:


There shouldn't be any metatype registration necessary. All you need to is to call setContextProperty and pass the model by pointer:

QQmlContext* context = view->rootContext(); //view is the QDeclarativeView
context->setContextProperty( "_rosterItemModel", &mainClassInstance->m_rosterItemModel );

Use it in QML:

model: _rosterItemModel

By pointer is important, as QObject's are not copy-constructible and copying them would break their semantics anyway (as they have an "identity").

The alternative to registering the model directly is to register your main class' instance and using Q_INVOKABLE. In MainClass:

Q_INVOKABLE RosterItemModel* rosterItemModel() const;

Registering an instance of mainClass (mainClassInstance again is assumed to be a pointer):

context->setContextProperty( "_mainInstance", mainClassInstance );

In QML:

model: _mainInstance.rosterItemModel()


来源:https://stackoverflow.com/questions/11806324/how-to-expose-a-c-model-to-qml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!