Integrating C++ with QML

Integrating C++ with QML

Wednesday, July 24, 2013

Introduction

Qt Quick's QML language makes it easy to do many things, especially fancy animated user interfaces. However, some things either can't be done or are not suitable for implementing in QML, such as:

  1. Getting access to functionality outside of the QML/JavaScript environment.
  2. Implementing performance critical functions where native code is desired for efficiency.
  3. Large and/or complex non-declarative code that would be tedious to implement in JavaScript.

As we'll see, Qt makes it quite easy to expose C++ code to QML. In this blog post I will show an example of doing this with a small but functional application.

The example is written for Qt 5 and uses the Qt Quick Components so you will need at least Qt version 5.1.0 to run it.

Overview

To expose a C++ type having properties, methods, signals, and/or slots to the QML environment, the basic steps are:

  1. Define a new class derived from QObject.
  2. Put the Q_OBJECT macro in the class declaration to support signals and slots and other services of the Qt meta-object system.
  3. Declare any properties using the Q_PROPERTY macro.
  4. Call qmlRegisterType() in your C++ main program to register the type with the Qt Quick engine.

For all the details I refer you to the Qt documentation section Exposing Attributes of C++ Types to QML and the Writing QML Extensions with C++ tutorial.

Ssh Key Generator

For our code example, we want a small application that will generate ssh public/private key pairs using a GUI. It will present the user with controls for the appropriate options and then run the program ssh-keygen to generate the key pair.

I implemented the user interface using the new Qt Quick Controls since it was intended as a desktop application with a desktop look and feel. I initially developed the UX entirely by running the qmlscene program directly on the QML source. A screen shot is shown below.

The UI prompts the user for the key type, the file name of the private key to generate and an optional pass phrase, which needs to be confirmed.

The C++ Class

Now that have the UI, we will want to implement the back end functionality. You can't invoke an external program directly from QML so we have to write it in C++ (which is the whole point of this example application).

First, we define a class that encapsulates the key generation functionality. It will be exposed as a new class KeyGenerator in QML. This is done in the header file KeyGenerator.h below.

#ifndef KEYGENERATOR_H
#define KEYGENERATOR_H

#include <QObject>
#include <QString>
#include <QStringList>

// Simple QML object to generate SSH key pairs by calling ssh-keygen.

class KeyGenerator : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QString type READ type WRITE setType NOTIFY typeChanged)
    Q_PROPERTY(QStringList types READ types NOTIFY typesChanged)
    Q_PROPERTY(QString filename READ filename WRITE setFilename NOTIFY filenameChanged)
    Q_PROPERTY(QString passphrase READ filename WRITE setPassphrase NOTIFY passphraseChanged)

public:
    KeyGenerator();
    ~KeyGenerator();

    QString type();
    void setType(const QString &t);

    QStringList types();

    QString filename();
    void setFilename(const QString &f);

    QString passphrase();
    void setPassphrase(const QString &p);

public slots:
    void generateKey();

signals:
    void typeChanged();
    void typesChanged();
    void filenameChanged();
    void passphraseChanged();
    void keyGenerated(bool success);

private:
    QString _type;
    QString _filename;
    QString _passphrase;
    QStringList _types;
};
#endif

Next, we need to derive our class from QObject. We declare any properties that we want and the associated methods. Notify methods become signals. In our case, we want to have properties for the selected key type, the list of all valid ssh key types, file name and pass phrase. I arbitrarily made the key type a string. It could have been an enumerated type but it would have made the example more complicated.

Incidentally, a new feature of the Q_PROPERTY macro in Qt 5.1.0 is the MEMBER argument. It allows specifying a class member variable that will be bound to a property without the need to implement the setter or getter functions. That feature was not used here.

We declare methods for the setters and getters and for signals. We also declare one slot called generateKey(). These will all be available to QML. If we wanted to export a regular method to QML, we could mark it with Q_INVOCABLE. In this case I decided to make generateKey() a slot since it might be useful in the future but it could have just as easily been an invocable method.

Finally, we declare any private member variables we will need.

C++ Implementation

Now let's look at the implementation in KeyGenerator.cpp. Here is the source code:

#include <QFile>
#include <QProcess>
#include "KeyGenerator.h"

KeyGenerator::KeyGenerator()
    : _type("rsa"), _types{"dsa", "ecdsa", "rsa", "rsa1"}
{
}

KeyGenerator::~KeyGenerator()
{
}

QString KeyGenerator::type()
{
    return _type;
}

void KeyGenerator::setType(const QString &t)
{
    // Check for valid type.
    if (!_types.contains(t))
        return;

    if (t != _type) {
        _type = t;
        emit typeChanged();
    }
}

QStringList KeyGenerator::types()
{
    return _types;
}

QString KeyGenerator::filename()
{
    return _filename;
}

void KeyGenerator::setFilename(const QString &f)
{
    if (f != _filename) {
        _filename = f;
        emit filenameChanged();
    }
}

QString KeyGenerator::passphrase()
{
    return _passphrase;
}

void KeyGenerator::setPassphrase(const QString &p)
{
    if (p != _passphrase) {
        _passphrase = p;
        emit passphraseChanged();
    }
}

void KeyGenerator::generateKey()
{
    // Sanity check on arguments
    if (_type.isEmpty() or _filename.isEmpty() or
        (_passphrase.length() > 0 and _passphrase.length() < 5)) {
        emit keyGenerated(false);
        return;
    }

    // Remove key file if it already exists
    if (QFile::exists(_filename)) {
        QFile::remove(_filename);
    }

    // Execute ssh-keygen -t type -N passphrase -f keyfileq
    QProcess *proc = new QProcess;
    QString prog = "ssh-keygen";
    QStringList args{"-t", _type, "-N", _passphrase, "-f", _filename};
    proc->start(prog, args);
    proc->waitForFinished();
    emit keyGenerated(proc->exitCode() == 0);
    delete proc;
}

The constructor initializes some of the member variables. For fun, I used the new initializer list feature of C++11 to initialize the _types member variable which is of type QStringList. The destructor does nothing, at least for now, but is there for completeness and future expansion.

Getter functions like type() simply return the appropriate private member variable. Setters set the appropriate variables, taking care to check that the new value is different from the old one and if so, emitting the appropriate signal. As always, please note that signals are created by the Meta Object Compiler and do not need to be implemented, only emitted at the appropriate times.

The only non-trivial method is the slot generateKey(). It does some checking of arguments and then creates a QProcess to run the external ssh-keygen program. For simplicity and because it typically executes quickly, I do this synchronously and block on it to complete. When done, we emit a signal that has a boolean argument that indicates the key was generated and whether it succeeded or not.

QML Code

Now let's look at the QML code in main.qml:

// SSH key generator UI

import QtQuick 2.1
import QtQuick.Controls 1.0
import QtQuick.Layouts 1.0
import QtQuick.Dialogs 1.0
import com.ics.demo 1.0

ApplicationWindow {
    title: qsTr("SSH Key Generator")

    statusBar: StatusBar {
    RowLayout {
        Label {
            id: status
            }
        }
    }

    width: 369
    height: 166

    ColumnLayout {
        x: 10
        y: 10

        // Key type
        RowLayout {
            Label {
                text: qsTr("Key type:")
            }
            ComboBox {
                id: combobox
                Layout.fillWidth: true
                model: keygen.types
                currentIndex: 2
            }
        }

        // Filename
        RowLayout {
            Label {
                text: qsTr("Filename:")
            }
            TextField {
                id: filename
                implicitWidth: 200
                onTextChanged: updateStatusBar()
            }
            Button {
                text: qsTr("&Browse...")
                onClicked: filedialog.visible = true
            }
        }

        // Passphrase
        RowLayout {
            Label {
                text: qsTr("Pass phrase:")
            }
            TextField {
                id: passphrase
                Layout.fillWidth: true
                echoMode: TextInput.Password
                onTextChanged: updateStatusBar()
            }

        }

        // Confirm Passphrase
        RowLayout {
            Label {
                text: qsTr("Confirm pass phrase:")
            }
            TextField {
                id: confirm
                Layout.fillWidth: true
                echoMode: TextInput.Password
                onTextChanged: updateStatusBar()
            }
        }

        // Buttons: Generate, Quit
        RowLayout {
            Button {
                id: generate
                text: qsTr("&Generate")
                onClicked: keygen.generateKey()
            }
            Button {
                text: qsTr("&Quit")
                onClicked: Qt.quit()
            }
        }

    }

    FileDialog {
        id: filedialog
        title: qsTr("Select a file")
        selectMultiple: false
        selectFolder: false
        nameFilters: [ "All files (*)" ]
        selectedNameFilter: "All files (*)"
        onAccepted: {
            filename.text = fileUrl.toString().replace("file://", "")
        }
    }

    KeyGenerator {
        id: keygen
        filename: filename.text
        passphrase: passphrase.text
        type: combobox.currentText
        onKeyGenerated: {
            if (success) {
                status.text = qsTr('<font color="green">Key generation succeeded.</font>')
            } else {
                status.text = qsTr('<font color="red">Key generation failed</font>')
            }
        }
    }

    function updateStatusBar() {
        if (passphrase.text != confirm.text) {
            status.text = qsTr('<font color="red">Pass phrase does not match.</font>')
            generate.enabled = false
        } else if (passphrase.text.length > 0 && passphrase.text.length < 5) {
            status.text = qsTr('<font color="red">Pass phrase too short.</font>')
            generate.enabled = false
        } else if (filename.text == "") {
            status.text = qsTr('<font color="red">Enter a filename.</font>')
            generate.enabled = false
        } else {
            status.text = ""
            generate.enabled = true
        }
    }

    Component.onCompleted: updateStatusBar()
}

The preceding code is a little long, however, much of the work is laying out the GUI components. The code should be straightforward to follow.

Note that we import com.ics.demo version 1.0. We'll see where this module name comes from shortly. This makes a new QML type KeyGenerator available and so we declare one. We have access to it's C++ properties as QML properties, can call it's methods and act on signals like we do with onKeyGenerated.

A more complete program should probably do a little more error checking and report meaningful error messages if key generation fails (we could easily add a new method or property for this). The UI layout could also be improved to make it properly resizable.

Our main program is essentially a wrapper like qmlscene. All we need to do to register our type with the QML engine is to call:

    qmlRegisterType<KeyGenerator>("com.ics.demo", 1, 0, "KeyGenerator");

This makes the C++ type KeyGenerator available as the QML type KeyGenerator in the module com.ics.demo version 1.0 when it is imported.

Typically, to run QML code from an executable, in the main program you would create a QGuiApplication and a QQuickView. Currently, to use the Qt Quick Components there is some additional work needed if the top level element is an ApplicationWindow or Window. You can look at the source code to see how I implemented this. I basically stripped down the code from qmlscene to the minimum of what was needed for this example.

Here is the full listing for the main program, main.cpp:

#include <QApplication>
#include <QObject>
#include <QQmlComponent>
#include <QQmlEngine>
#include <QQuickWindow>
#include <QSurfaceFormat>
#include "KeyGenerator.h"

// Main wrapper program.
// Special handling is needed when using Qt Quick Controls for the top window.
// The code here is based on what qmlscene does.

int main(int argc, char ** argv)
{
    QApplication app(argc, argv);

    // Register our component type with QML.
    qmlRegisterType<KeyGenerator>("com.ics.demo", 1, 0, "KeyGenerator");

    int rc = 0;

    QQmlEngine engine;
    QQmlComponent *component = new QQmlComponent(&engine);

    QObject::connect(&engine, SIGNAL(quit()), QCoreApplication::instance(), SLOT(quit()));

    component->loadUrl(QUrl("main.qml"));

    if (!component->isReady() ) {
        qWarning("%s", qPrintable(component->errorString()));
        return -1;
    }

    QObject *topLevel = component->create();
    QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel);

    QSurfaceFormat surfaceFormat = window->requestedFormat();
    window->setFormat(surfaceFormat);
    window->show();

    rc = app.exec();

    delete component;
    return rc;
}

In case it is not obvious, when using a module written in C++ with QML you cannot use the qmlscene program to execute your QML code because the C++ code for the module will not be linked in. If you try to do this you will get an error message that the module is not installed.

Conclusions

The preceding simple example shows how easy it is to create a new QML component in C++ and expose properties, signals and slots. While much can be done with QML, C++ is still useful and typically, it will be used in conjunction with QML in any non-trivial application.

You can download the full source code for the example from here.

Interested in Qt & QML?

Read more articles from the category Qt & QML

Tags:

About the author

Jeff Tranter

Bio:

Jeff Tranter is a Qt Consulting Manager at ICS. Jeff oversees the architectural and high-level design of software systems for clients. Jeff’s leadership organizes global teams of developers on desktop and embedded applications.

Comments

Submitted by djohnson on
Comment: 

An alternate method for C++/QML integration is to use the meta object system as a bridge. Your C++ "backend" has access to the QML root object, and can directly access its properties, connect to its signals, and call its functions. This is somewhat the opposite of above. Instead of exposing C++ objects to QML, you're using the QML root object that is already exposed to C++. The advantage to this is a nice clean bridge layer, allowing replacement of the QML frontend, and use of the QML in qmlscene for development and testing purposes.

Submitted by Faramos on
Comment: 

I got some compile errors, I think its the c++11 config line.

Im using windows 7 64bit, visualstudio 2012 32bit, compiler: Mircosoft visual c++ compiler 11.0

Perhaps u have an idea why this doesnt compile?

TIA!

 

 

KeyGenerator.cpp(6) : error C2059: Syntaxfehler: '{'

KeyGenerator.cpp(6) : error C2143: Syntaxfehler: Es fehlt ';' vor '}'

KeyGenerator.cpp(7) : error C2447: '{': Funktionsheader fehlt - Parameterliste im alten Stil?

KeyGenerator.cpp(65) : error C2146: Syntaxfehler: Fehlendes ')' vor Bezeichner 'or'

KeyGenerator.cpp(65) : error C2065: 'or': nichtdeklarierter Bezeichner

KeyGenerator.cpp(65) : error C2146: Syntaxfehler: Fehlendes ';' vor Bezeichner '_filename'

KeyGenerator.cpp(66) : error C2146: Syntaxfehler: Fehlendes ';' vor Bezeichner 'or'

KeyGenerator.cpp(66) : error C2146: Syntaxfehler: Fehlendes ')' vor Bezeichner 'and'

KeyGenerator.cpp(66) : error C2059: Syntaxfehler: ')'

KeyGenerator.cpp(66) : error C2143: Syntaxfehler: Es fehlt ';' vor '{'

KeyGenerator.cpp(66) : error C3861: "or": Bezeichner wurde nicht gefunden.

KeyGenerator.cpp(79) : error C2601: 'args': Lokale Funktionsdefinitionen sind unzul„ssig

KeyGenerator.cpp(63): Diese Zeile enth„lt eine '{', die keine Entsprechung hat

KeyGenerator.cpp(79) : error C2143: Syntaxfehler: Es fehlt ';' vor '}'

KeyGenerator.cpp(80) : error C2065: 'proc': nichtdeklarierter Bezeichner

KeyGenerator.cpp(80) : error C2227: Links von "->start" muss sich ein Zeiger auf Klassen-/Struktur-/Union-/generischen Typ befinden.

Typ ist ''unknown-type''

KeyGenerator.cpp(80) : error C2065: 'prog': nichtdeklarierter Bezeichner

KeyGenerator.cpp(80) : error C2065: 'args': nichtdeklarierter Bezeichner

KeyGenerator.cpp(81) : error C2065: 'proc': nichtdeklarierter Bezeichner

KeyGenerator.cpp(81) : error C2227: Links von "->waitForFinished" muss sich ein Zeiger auf Klassen-/Struktur-/Union-/generischen Typ befinden.

Typ ist ''unknown-type''

KeyGenerator.cpp(82) : error C2065: 'proc': nichtdeklarierter Bezeichner

KeyGenerator.cpp(82) : error C2227: Links von "->exitCode" muss sich ein Zeiger auf Klassen-/Struktur-/Union-/generischen Typ befinden.

Typ ist ''unknown-type''

KeyGenerator.cpp(82) : error C3861: "keyGenerated": Bezeichner wurde nicht gefunden.

KeyGenerator.cpp(83) : error C2065: 'proc': nichtdeklarierter Bezeichner

KeyGenerator.cpp(83) : error C2541: 'delete': Objekte, die keine Zeiger sind, k”nnen nicht gel”scht werden

Submitted by Faramos on
Comment: 

After looking at the enabled features in vs compiler 11 for c++11...

Stringlist arguments in init list no supported yet and "or" "and" isn´t supported...

After fixing this the code compiles. (putting the initializing of the init list in the cTor and replace "or" with || and "and" with "&&".

Perhaps this helps s.o.  If i am wrong, any information would nice.

Submitted by jtranter on
Comment: 
Make sure your qmake project file has the line "CONFIG += c++11". That will enable C++11 support in the compiler options. The original source code posted for the example omitted this and you may need it to compile on Windows.

Submitted by tanit on
Comment: 

I didn't change anything in your source code, so all should be ok.I tried to compile and run. Compile process ok, but after run, main.qml not found, I search in the internet but no help,
I didn't find any other exemple of integrating QML with C++, only yours , Please help me I'll be gratefull .

Submitted by jtranter on
Comment: 

You will need to run the program from the directory where the main.qml file is located, or change the code to point to the full path to the file on your system. If you built it with Q Creator and used shadow builds, for example, you will encounter this issue. Making the qml file a resource and loading it that way will also avoid this problem.

This blog post has another example of integrating QML with C++: http://www.ics.com/blog/multilayered-architecture-qt-quick

Pages