Jolla and SailfishOS

2017-04-06 11:35

Linking C++ and QML code

While JavaScript (which QML is a version of) is a good tool for the presentation layer, I'm not eager to write all my business logic in it. There are many reasons why that is. But that is a discussion for some other time. Let's for now just stick with the argument, that there a many problems already solved in C/C++ libraries and there should be no reason to reinvent the wheel, just because you change the presentation layer.

There are two main reasons why I decided to have a look at Qt/QML (and hence Silica):

The multi-platform support I leave for some other project. For now, just look up the Internet if you are eager to learn more about it.

For D-Bus Inspector I was interested in how to make code written in C(++) available to a QML application.

It turns out that this not to hard to do.

C++ code

To test how to use C++ code from within QML we first need some C++ code.

Since this App is about accessing the D-Bus, I decided that the task of my first class should be to provide a list of the services available on the D-Session-Bus.

It is declared in dSessionBusServicesModel.h

dSessionBusServicesModel.cpp implements the DSessionBusServicesModel methods declared in it's .h file:

QML type registering

So the model is pretty simple. We now just have to make it available in QML.

This is done by registering the type (class) with the QML system.

In the D-Bus Inspector project I do this in harbour-dbus-inspector.cpp, which provide the main() entry point for the application.

QML type usage

All preparations down, we can now use our newly declared C++/QML type, like any native one.

There is not much more to it. The rest is like using any other list model in QML:



we can create, what can be seen as a C++ context within QML.

Once we have created an instance of our "interface" Q_OBJECT, we are free to use it's Q_INVOKEABLE methods to invoke from the QML context any C/C++ code we desire.