Qt Quick 出版物
使用Qt Quick Controls 创建一个能够向 MQTT 主题发布消息的应用程序。

Qt Quick “发布”演示了如何将QMqttClient 注册为QML类型,并在Qt Quick 应用程序中使用它。
Qt MQTT 当前版本未提供 QML API。不过,您可以将该模块的 C++ 类提供给 QML 使用。
创建客户端
创建名为QmlMqttClient 的封装类,该类包含QMqttClient 作为成员:
private:
Q_DISABLE_COPY(QmlMqttClient)
QMqttClient m_client;
};在构造函数中将包装类的方法与QMqttClient 的方法关联起来:
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);
}包装方法的名称与被包装方法的名称相同。在最简单的情况下,它只是一个单一的方法调用:
void QmlMqttClient::connectToHost()
{
m_client.connectToHost();
}此外,还可以通过扩展包装方法并添加一些额外功能来对其进行自定义:
voidQmlMqttClient::setPort(intnewPort)
{
if(newPort< 0||newPort>std::numeric_limits<quint16>::max()) {
qWarning() << "Trying to set invalid port number";
return;
}
m_client.setPort(static_cast<quint16>(newPort));在 QML 中注册类
在main.cpp 文件中,从模块发布中加载 QML 类型 Main:
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);现在在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.