Quick MQTT Example

Registering QMqttClient to QML and using it in a Qt Quick user interface.

Quick MQTT 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

We create a QmlMqttClient class with the QMqttClient class as a base class:

 QmlMqttClient::QmlMqttClient(QObject *parent)
     : QMqttClient(parent)
 {
 }

We use the subscribe() function to create a subscription object:

 QmlMqttSubscription* QmlMqttClient::subscribe(const QString &topic)
 {
     auto sub = QMqttClient::subscribe(topic, 0);
     auto result = new QmlMqttSubscription(sub, this);
     return result;
 }

We connect to QMqttSubscription::messageReceived( ) to receive all messages sent to the broker:

 QmlMqttSubscription::QmlMqttSubscription(QMqttSubscription *s, QmlMqttClient *c)
     : sub(s)
     , client(c)
 {
     connect(sub, &QMqttSubscription::messageReceived, this, &QmlMqttSubscription::handleMessage);
     m_topic = sub->topic();
 }

We use an QMqttMessage object to store the payload of a received message:

 void QmlMqttSubscription::handleMessage(const QMqttMessage &qmsg)
 {
     emit messageReceived(qmsg.payload());
 }

Registering Classes in QML

In the main.cpp file, we register the QmlMqttClient class as a QML type, MqttClient:

 int main(int argc, char *argv[])
 {
     QGuiApplication app(argc, argv);

     QQmlApplicationEngine engine;

     qmlRegisterType<QmlMqttClient>("MqttClient", 1, 0, "MqttClient");

In addition, we register the QmlMqttSubscription class as an uncreatable type:

     qmlRegisterUncreatableType<QmlMqttSubscription>("MqttClient", 1, 0, "MqttSubscription", QLatin1String("Subscriptions are read-only"));

We can now use the MqttClient type in the main.qml file to create an MQTT client:

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

Files: