Qt Quick Publication

Use Qt Quick Controls to create an application that can publish on MQTT topics.

Qt Quick Publication demonstrates how to register QMqttClient as a QML type and use it in a Qt Quick application.

Qt MQTT does not provide a QML API in its current version. However, you can make the C++ classes of the module available to QML.

Creating a Client

Create the wrapper class QmlMqttClient that has QMqttClient as a member:

    QMqttClient m_client;

Connect the wrapper methods to the methods of QMqttClient in the constructor:

QmlMqttClient::QmlMqttClient(QObject *parent)
    : QObject(parent)
    connect(&m_client, &QMqttClient::hostnameChanged, this, &QmlMqttClient::hostnameChanged);
    connect(&m_client, &QMqttClient::portChanged, this, &QmlMqttClient::portChanged);
    connect(&m_client, &QMqttClient::stateChanged, this, &QmlMqttClient::stateChanged);

A wrapper method has the same name as the wrapped method. In the simplest case, it is just a single method call:

void QmlMqttClient::connectToHost()

It is also possible to customize a wrapper method by extending it with some additional functionality:

void QmlMqttClient::setPort(int newPort)
    if (newPort < 0 || newPort > std::numeric_limits<quint16>::max()) {
        qWarning() << "Trying to set invalid port number";

Registering Classes in QML

In the main.cpp file, load the QML type Main from the module publication:

    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;

            &engine, &QQmlApplicationEngine::objectCreationFailed, &app,
            []() { QCoreApplication::exit(EXIT_FAILURE); }, Qt::QueuedConnection);

    engine.loadFromModule(u"publication"_s, u"Main"_s);

Now use the MqttClient type in the Main.qml file to create an MQTT client:

    MqttClient {
        id: client
        hostname: hostnameField.text
        port: portField.text


© 2024 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.