Qt Quick Pubblicazione
Utilizzare i controlli " Qt Quick " per creare un'applicazione in grado di pubblicare su argomenti MQTT.

Qt Quick La sezione Pubblicazione illustra come registrare QMqttClient come tipo QML e utilizzarlo in un'applicazione Qt Quick.
Qt MQTT Nella versione attuale non è disponibile un’API QML. Tuttavia, è possibile rendere disponibili a QML le classi C++ del modulo.
Creazione di un client
Creare la classe wrapper ` QmlMqttClient ` che abbia come membro ` QMqttClient `:
private:
Q_DISABLE_COPY(QmlMqttClient)
QMqttClient m_client;
};Collegare i metodi del wrapper ai metodi di ` QMqttClient ` nel costruttore:
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);
}Un metodo wrapper ha lo stesso nome del metodo avvolto. Nel caso più semplice, si tratta semplicemente di una singola chiamata al metodo:
void QmlMqttClient::connectToHost()
{
m_client.connectToHost();
}È anche possibile personalizzare un metodo wrapper estendendolo con alcune funzionalità aggiuntive:
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));Registrazione delle classi in QML
Nel file main.cpp, caricare il tipo QML Main dalla pubblicazione del modulo:
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);Ora utilizza 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.