QT官方的mqtt是qmqtt,头文件是
#include <qmqttclient.h>
官方的文档地址 https://doc.qt.io/QtMQTT/qmqttclient.html#publish
使用要在工程文件中添加
QT += mqtt
void MyMqttClient::mqttStateChange(int state) { if(state == 0) { qDebug() << "mqtt disconnected"; } else if(state == 1) { qDebug() << "mqtt connecting"; } else if(state == 2) { qDebug() << "mqtt connected"; m_mqttClient->subscribe("订阅你自己的主题"); } } MyMqttClient::MyMqttClient(QObject *parent) : QObject(parent) { m_mqttClient = new QMqttClient; m_mqttClient->setHostname(HOSTNAME); m_mqttClient->setPort(PORT); m_mqttClient->setUsername(USERNAME); m_mqttClient->setPassword(PASSWORD); m_mqttClient->setClientId(CLIENTID); connect(m_mqttClient, &QMqttClient::stateChanged,[=](int state){ this->mqttStateChange(state); }); connect(m_mqttClient, &QMqttClient::messageReceived,[=](QByteArray message, QMqttTopicName topic){ const QString content = QDateTime::currentDateTime().toString() + QLatin1String(" Received Topic: ") + topic.name() + QLatin1String(" Message: ") + message + QLatin1Char(‘\n‘); qDebug() << content; }); m_mqttClient->setKeepAlive(60); m_mqttClient->connectToHost(); }