How to open C ++ - model for QML

I am writing a QML + Qt application. I defined the class as follows:

class MainClass : public QObject { Q_OBJECT public: rosterItemModel m_rosterItemModel; . . . } 

rosterItemModel is a class derived from QAbstractListModel. I discovered MainClass for the qml part using this function:

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

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

  • I tried to declare m_rosterItemModel as PROPERTY using Q_PROPERTY. I could not do this because he said that QAbstractListModel was not copying state.
  • I tried to get a pointer to m_rosterItemModel in the qml file using the Q_INVOKABLE function in MainClass. But that didn't help either.

Can someone help me?

+6
source share
1 answer

There should be no need to register a metatype. All you need to do is 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, it’s important, since QObjects are not copied and copying them will still break the semantics (since they have an "identifier").

An alternative to registering the model directly is registering an instance of your main class and using Q_INVOKABLE. In MainClass:

 Q_INVOKABLE RosterItemModel* rosterItemModel() const; 

Registering an instance of mainClass (mainClassInstance is again considered a pointer):

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

In QML:

 model: _mainInstance.rosterItemModel() 
+6
source

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


All Articles