Qt Quick 出版物

使用Qt Quick Controls 创建可在 MQTT 主题上发布的应用程序。

Qt Quick 出版物演示了如何将 注册为 QML 类型并在 应用程序中使用。QMqttClient Qt Quick

Qt MQTT在当前版本中,《MQTT.NET》不提供 QML API。不过,您可以将模块的 C++ 类提供给 QML。

创建客户端

创建以QMqttClient 为成员的封装类QmlMqttClient

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) {如果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
    }

文件:

© 2025 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.