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);
?
Detailed Description. Contexts allow data to be exposed to the QML components instantiated by the QML engine. Each QQmlContext contains a set of properties, distinct from its QObject properties, that allow data to be explicitly bound to a context by name.
The Qt QML module provides a framework for developing applications and libraries with the QML language. It defines and implements the language and engine infrastructure, and provides an API to enable application developers to extend the QML language with custom types and integrate QML code with JavaScript and C++.
QML is the language; its JavaScript runtime is the custom V4 engine, since Qt 5.2; and Qt Quick is the 2D scene graph and the UI framework based on it. These are all part of the Qt Declarative module, while the technology is no longer called Qt Declarative.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With