本页内容

MQTT 订阅

创建一个与 MQTT 代理进行通信的应用程序。

主窗口包含连接和发布控件,以及两个订阅窗口,显示在 qtmqtt/topic1 上接收到的消息

“MQTT 订阅”演示了如何创建一个与 MQTT 代理进行通信的应用程序。每次订阅都会打开一个新的对话框,您可以在其中查看已订阅主题上的消息。

创建客户端

我们使用QMqttClient 类来创建MQTT客户端,并设置用于连接的代理主机名和端口:

    m_client = new QMqttClient(this);
    m_client->setHostname(ui->lineEditHost->text());
    m_client->setPort(static_cast<quint16>(ui->spinBoxPort->value()));

订阅主题

当用户在客户端订阅主题时,会创建一个新的订阅对象:

void MainWindow::on_buttonSubscribe_clicked()
{
    auto subscription = m_client->subscribe(ui->lineEditTopic->text(),
                                            static_cast<quint8>(ui->spinQoS->text().toUInt()));
    if (!subscription) {
        QMessageBox::critical(this, u"Error"_s,
                              u"Could not subscribe. Is there a valid connection?"_s);
        return;
    }
    auto subWindow = new SubscriptionWindow(subscription);
    subWindow->setWindowTitle(subscription->topic().filter());
    subWindow->show();
}

我们使用QMqttSubscription 类来存储订阅的主题、状态和QoS级别:

SubscriptionWindow::SubscriptionWindow(QMqttSubscription *sub, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SubscriptionWindow),
    m_sub(sub)
{
    ui->setupUi(this);

    ui->labelSub->setText(m_sub->topic().filter());
    ui->labelQoS->setText(QString::number(m_sub->qos()));
    updateStatus(m_sub->state());
    connect(m_sub, &QMqttSubscription::messageReceived, this, &SubscriptionWindow::updateMessage);
    connect(m_sub, &QMqttSubscription::stateChanged, this, &SubscriptionWindow::updateStatus);
    connect(m_sub, &QMqttSubscription::qosChanged, [this](quint8 qos) {
        ui->labelQoS->setText(QString::number(qos));
    });
    connect(ui->pushButton, &QAbstractButton::clicked, m_sub, &QMqttSubscription::unsubscribe);
}

消息和订阅的 QoS 级别可以分别设置。订阅设置的 QoS 级别决定了最低 QoS 级别。如果发送的消息具有更高的 QoS 级别,消息代理会将该消息的 QoS 级别提升至该更高级别。 例如,如果客户端 A 订阅了 QoS 为 1的主题,而客户端 B 在该主题上发布了一条 QoS 为 0 的消息,则消息代理会自动将该消息的 QoS 提升至 1。 如果客户端 B 在该主题上发布了一条 QoS 为 2 的消息,则代理将以 QoS 2 的级别发送该消息。

接收消息

当客户端接收消息时,会使用QMqttMessage 类来存储实际的消息负载:

void SubscriptionWindow::updateMessage(const QMqttMessage &msg)
{
    ui->listWidget->addItem(msg.payload());
}

文件:

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