Qt Quick Suscripción
Utiliza los controles « Qt Quick » para crear una aplicación capaz de suscribirse a temas MQTT.

Qt Quick La sección «Suscripción» muestra cómo registrar « QMqttClient » como un tipo QML y utilizarlo en una aplicación « Qt Quick ».
Qt MQTT No proporciona una API de QML en su versión actual. Sin embargo, puedes hacer que las clases C++ del módulo estén disponibles para QML.
Creación de un cliente
Conéctate a QMqttSubscription::messageReceived( ) para recibir todos los mensajes enviados al bróker:
QmlMqttSubscription::QmlMqttSubscription(QMqttSubscription *s, QmlMqttClient *c)
: sub(s)
, client(c)
{
connect(sub, &QMqttSubscription::messageReceived, this, &QmlMqttSubscription::handleMessage);
}Crea una clase ` QmlMqttClient ` con la clase ` QMqttClient ` como clase base:
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);
}Utiliza la función ` subscribe() ` para crear un objeto de suscripción:
QmlMqttSubscription* QmlMqttClient::subscribe(const QString &topic)
{
auto sub = m_client.subscribe(topic, 0);
auto result = new QmlMqttSubscription(sub, this);
return result;
}Utiliza un objeto ` QMqttMessage ` para almacenar la carga útil de un mensaje recibido:
void QmlMqttSubscription::handleMessage(const QMqttMessage &qmsg)
{
emit messageReceived(qmsg.payload());
}Registro de clases en QML
En el archivo ` main.cpp `, carga el tipo QML `Main` del módulo `subscription`:
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
QObject::connect(
&engine, &QQmlApplicationEngine::objectCreationFailed, &app,
[]() { QCoreApplication::exit(EXIT_FAILURE); }, Qt::QueuedConnection);
engine.loadFromModule(u"subscription"_s, u"Main"_s);Ahora utiliza el tipo `MqttClient` en el archivo ` Main.qml ` para crear un cliente MQTT:
MqttClient {
id: client
hostname: hostnameField.text
port: portField.text
}Archivos:
© 2026 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.