In questa pagina

Qt Quick Abbonamento

Utilizzare i controlli Qt Quick per creare un'applicazione in grado di sottoscrivere argomenti MQTT.

Interfaccia di sottoscrizione MQTT con campi Nome host, Porta, Argomento e pulsanti Connetti e Sottoscrivi

Qt Quick La sezione "Abbonamento" illustra come registrare QMqttClient come tipo QML e utilizzarlo in un'applicazione Qt Quick.

Qt MQTT non fornisce un'API QML nella sua versione attuale. Tuttavia, è possibile rendere disponibili a QML le classi C++ del modulo.

Creazione di un client

Connettersi a QMqttSubscription::messageReceived( ) per ricevere tutti i messaggi inviati al broker:

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

Creare una classe ` QmlMqttClient ` con la classe ` QMqttClient ` come classe 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);
}

Utilizzare la funzione ` subscribe() ` per creare un oggetto di sottoscrizione:

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

Utilizzare un oggetto ` QMqttMessage ` per memorizzare il payload di un messaggio ricevuto:

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

Registrazione delle classi in QML

Nel file main.cpp, caricare il tipo QML Main dal modulo 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);

Ora utilizzare il tipo `MqttClient` nel file ` Main.qml ` per creare un client MQTT:

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

File:

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