14

In Qt/QML application (this code usually resides in main.cpp of QtCreator project), what is the difference between following ways of exposing C++ class to QML:

qmlRegisterType<UePeopleModel>("com.example",
                               1,
                               0,
                               "UePeopleModel");

and

engine.rootContext()->setContextProperty("uePeopleModel",
                                         uePeopleModel);

?

KernelPanic
  • 2,328
  • 7
  • 47
  • 90

2 Answers2

17

qmlRegisterType :

"Sometimes a QObject-derived class may need to be registered with the QML type system but not as an instantiable type."

Use qmlRegisterType, if you want reuse a QObject-derived class with in one or more than one qml file with different property. QML is responsible for initialization of this register class.

See this for more help. Defining QML Types from C++

setContextProperty :

Use setContextProperty, When you want to use a single global class to access to or from QML. Here You need create this class object before use setContextProperty().

Note: Since all expressions evaluated in QML are evaluated in a particular context, if the context is modified, all bindings in that context will be re-evaluated. Thus, context properties should be used with care outside of application initialization, as this may lead to decreased application performance.

See this for more help. Embedding C++ Objects into QML

Ankur
  • 1,385
  • 11
  • 21
  • so I have Qt/QML and this app at the beginning requires user login. I am thinking of creating some global status class, which will contain (at the beginning) id and name of logged user (taken from database) so for this particular example I embedded object into qml rather than defining new qml type? – KernelPanic Aug 17 '15 at 07:51
  • 1
    Yes, setContextProperty() is best option. – Ankur Aug 17 '15 at 10:23
  • 1
    [This](https://forum.qt.io/post/212826) post covers also the comparison between Context Properties and Singletons. – ceztko Jun 27 '17 at 21:19
4

In the first one you are declaring a C++ type available for instantiation in QML, in the second you are declaring a global variable "uePeopleModel" of the same type.

cmannett85
  • 21,725
  • 8
  • 76
  • 119