Qt Quick 订阅
使用Qt Quick Controls 创建一个能够订阅MQTT主题的应用程序。

Qt Quick “订阅”示例演示了如何将QMqttClient 注册为QML类型,并在Qt Quick 应用程序中使用它。
Qt MQTT 当前版本中未提供 QML API。不过,您可以将该模块的 C++ 类提供给 QML 使用。
创建客户端
连接到QMqttSubscription::messageReceived( ) 以接收发送到消息代理的所有消息:
QmlMqttSubscription::QmlMqttSubscription(QMqttSubscription *s, QmlMqttClient *c)
: sub(s)
, client(c)
{
connect(sub, &QMqttSubscription::messageReceived, this, &QmlMqttSubscription::handleMessage);
}创建一个以QMqttClient 类为基类的QmlMqttClient 类:
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);
}使用subscribe() 函数创建订阅对象:
QmlMqttSubscription* QmlMqttClient::subscribe(const QString &topic)
{
auto sub = m_client.subscribe(topic, 0);
auto result = new QmlMqttSubscription(sub, this);
return result;
}使用QMqttMessage 对象存储接收到的消息的有效载荷:
void QmlMqttSubscription::handleMessage(const QMqttMessage &qmsg)
{
emit messageReceived(qmsg.payload());
}在 QML 中注册类
在main.cpp 文件中,从 subscription 模块加载 QML 类型 Main:
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);现在,在Main.qml 文件中使用MqttClient类型创建一个MQTT客户端:
MqttClient {
id: client
hostname: hostnameField.text
port: portField.text
}文件:
© 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.