快速 MQTT 范例

注册 QMqttClient 到 QML 并在 Qt Quick 用户界面中使用它。

Quick MQTT demonstrates how to register QMqttClient as a QML type and use it in a Qt Quick application.

Qt MQTT does not provide a QML API in its current version. However, you can make the C++ classes of the module available to QML.

创建客户端

创建 QmlMqttClient 类采用 QMqttClient class as a base class:

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() function to create a subscription object:

void QmlMqttClient::connectToHost()
{
    m_client.connectToHost();
}
					

连接到 QMqttSubscription::messageReceived ( ) to receive all messages sent to the broker:

void QmlMqttClient::disconnectFromHost()
{
    m_client.disconnectFromHost();
}
					

使用 QMqttMessage object to store the payload of a received message:

void QmlMqttSubscription::handleMessage(const QMqttMessage &qmsg)
{
    emit messageReceived(qmsg.payload());
}
					

在 QML 中注册类

main.cpp 文件,注册 QmlMqttClient 类作为 QML 类型,MqttClient:

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;
    qmlRegisterType<QmlMqttClient>("MqttClient", 1, 0, "MqttClient");
					

In addition, we register the QmlMqttSubscription class as an uncreatable type:

    qmlRegisterUncreatableType<QmlMqttSubscription>("MqttClient", 1, 0, "MqttSubscription", QLatin1String("Subscriptions are read-only"));
					

We can now use the MqttClient type in the main.qml file to create an MQTT client:

    MqttClient {
        id: client
        hostname: hostnameField.text
        port: portField.text
    }
					

文件: