En esta página

Qt Quick Suscripción

Utilice Qt Quick Controls para crear una aplicación que pueda suscribirse a temas MQTT.

Interfaz de suscripción MQTT con campos Hostname, Port, Topic, botones Connect y Subscribe

Qt Quick Subscription demuestra cómo registrar QMqttClient como tipo QML y utilizarlo en una aplicación Qt Quick.

Qt MQTT no proporciona una API 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éctese a QMqttSubscription::messageReceived( ) para recibir todos los mensajes enviados al broker:

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

Cree 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);
}

Utilizar 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;
}

Utilizar 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, cargue la clase 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
    }

Ficheros:

© 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.