Qt Quick Publicação
Use os controles d Qt Quick para criar um aplicativo capaz de publicar em tópicos MQTT.

Qt Quick A publicação demonstra como registrar ` QMqttClient ` como um tipo QML e utilizá-lo em um aplicativo Qt Quick.
Qt MQTT não oferece uma API QML em sua versão atual. No entanto, é possível disponibilizar as classes C++ do módulo para o QML.
Criação de um cliente
Crie a classe wrapper ` QmlMqttClient `, que tenha ` QMqttClient ` como membro:
private:
Q_DISABLE_COPY(QmlMqttClient)
QMqttClient m_client;
};Conecte os métodos do wrapper aos métodos de ` QMqttClient ` no construtor:
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);
}Um método wrapper tem o mesmo nome que o método encapsulado. No caso mais simples, trata-se apenas de uma única chamada de método:
void QmlMqttClient::connectToHost()
{
m_client.connectToHost();
}Também é possível personalizar um método wrapper, ampliando-o com algumas funcionalidades adicionais:
void QmlMqttClient::setPort(int newPort)
{
if (newPort < 0|| newPort > std::numeric_limits<quint16>::max()) {
qWarning() << "Trying to set invalid port number";
return;
}
m_client.setPort(static_cast<quint16>(newPort));Registrando classes no QML
No arquivo main.cpp, carregue o tipo QML Main a partir da publicação do módulo:
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
QObject::connect(
&engine, &QQmlApplicationEngine::objectCreationFailed, &app,
[]() { QCoreApplication::exit(EXIT_FAILURE); }, Qt::QueuedConnection);
engine.loadFromModule(u"publication"_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.