Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt/QML qmlRegisterType vs. setContextProperty (difference)

Tags:

c++

qt

qml

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);

?

like image 838
KernelPanic Avatar asked Aug 17 '15 06:08

KernelPanic


People also ask

What is QQmlContext?

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.

What is Qt QML C++?

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++.

What is QML engine?

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.


2 Answers

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

like image 144
Ankur Avatar answered Nov 01 '22 06:11

Ankur


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.

like image 35
cmannett85 Avatar answered Nov 01 '22 06:11

cmannett85