Hybrid Application Using QML and Qt C++

Though QML provides a nice way to design user interfaces, and JavaScript is employed there to implement the application logic and works pretty nice in many cases, we might still need Qt C++ in some situations (well, at least JavaScript has limited access outside its sandbox).

1) integrate QML into Qt C++
Suppose we have a QML file, named “myqml.qml”, like this:

One easy way to integrate is to use the QDeclarativeView class, which provides a widget to display QML files. You just need the following three lines:

However, QDeclarativeView consumes more resources than normal widgets. Fortunately, we can integrate QML into a graphics scene. The following lines shows the basic usage:

Then with the help of the QDeclarativeItem class, you can easily access the properties of the QML element, e.g.:

2) exposing Qt C++ objects to QML
You can also expose native Qt C++ objects to QML through QDeclarativeContext:

Then in QML, you can have e.g. the following line to access them:

You can also use QDeclarativePropertyMap to manage the exposed properties:

In a QML engine, there could be a couple of contexts, forming a tree structure. The child contexts inherit properties in the parent context. By default, there is only one root context, but you can always add more to give finer control of the exposed data, i.e. different QDeclarativeComponent inside the same context have the same exposed data set.

To expose a self-defined object, we can use the following code:

Moreover, we can create new QML types:

In QML, you can use it like this:

Now let’s jump to invoke a Qt C++ function from QML. Basically, QML can invoke slots and functions declared with Q_INVOKABLE. Suppose we have the following function in MyObject:

Then you can invoke it in QML:

3) write plugins as QML extension
The benefits for using plugins as QML extensions are similar to using shared libraries, and it can be easily achieved with the help of QDeclarativeExtensionPlugin. Let’s reuse the MyType class defined in the previous section. First, we need to create a plugin:

Then create a file named “qmldir” to define which plugin to load from where (suppose the plugin is called “myplugin):

Now we can use qmlviewer to launch the QML file:

4) summary

  • Use QDeclarativeView or QDeclarativeComponent to integrate a QML file into native Qt C++.
  • Qt C++ can access the properties of QML elements through QDeclarativeItem.
  • Expose native objects to QML through QDeclarativeContext.
  • New QML types can be exported through qmlRegisterType.
  • The properties of native objects are exported as properties, and the slots or functions declared with Q_INVOKABLE can be invoked in QML.
  • Create plugins for extension using QDeclarativeExtensionPlugin.

Leave a Reply