Qt Quick Assinatura
Use os controles “ Qt Quick ” para criar um aplicativo capaz de se inscrever em tópicos MQTT.

Qt Quick A seção “Assinatura” demonstra como registrar o ` QMqttClient ` como um tipo QML e usá-lo em um aplicativo Qt Quick.
Qt MQTT não oferece uma API QML em sua versão atual. No entanto, você pode tornar as classes C++ do módulo disponíveis para o QML.
Criação de um cliente
Conecte-se a QMqttSubscription::messageReceived( ) para receber todas as mensagens enviadas ao broker:
QmlMqttSubscription::QmlMqttSubscription(QMqttSubscription *s, QmlMqttClient *c)
: sub(s)
, client(c)
{
connect(sub, &QMqttSubscription::messageReceived, this, &QmlMqttSubscription::handleMessage);
}Crie uma classe ` QmlMqttClient ` tendo a classe ` QMqttClient ` como 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);
}Use a função ` subscribe() ` para criar um objeto de assinatura:
QmlMqttSubscription* QmlMqttClient::subscribe(const QString &topic)
{
auto sub = m_client.subscribe(topic, 0);
auto result = new QmlMqttSubscription(sub, this);
return result;
}Use um objeto ` QMqttMessage ` para armazenar a carga útil de uma mensagem recebida:
void QmlMqttSubscription::handleMessage(const QMqttMessage &qmsg)
{
emit messageReceived(qmsg.payload());
}Registrando classes no QML
No arquivo ` main.cpp `, carregue o tipo QML `Main` do 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);Agora, use o tipo `MqttClient` no arquivo ` Main.qml ` para criar um cliente MQTT:
MqttClient {
id: client
hostname: hostnameField.text
port: portField.text
}Arquivos:
© 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.