qt的mqtt編譯及使用方法

在qt5.10之前,mqtt需要自己編譯庫,

1.源碼路徑

下載地址:https://github.com/emqx/qmqtt,注意要下載qmqtt-master版本的,不要下載qtmqtt-dev

 

2.生成庫文件

使用qtcreator打開qmqtt.pro文件,構建src工程,

編譯報錯:Could not create directory "...\qmqtt\Error in " Util.asciify("build-qmqtt-Qt_5_6_3_msvc2013-Debug")": TypeError: Property 'asciify' of object Core::Internal::UtilsJsExtension(0x34bb080) is not a function\src"

Error while building/deploying project qmqtt (kit: Qt 5.6.3 (msvc2013))

When executing step "qmake"

解決方法:

左邊樹,選擇項目,將影子構建取消勾選。

 

再次構建src工程,可生成lib文件夾,裏面含debug和Release版本的dll和lib文件。

Qt5Qmqtt.dll、Qt5Qmqtt.lib、Qt5Qmqttd.dll、Qt5Qmqttd.lib

3.文件拷貝

將文件拷貝到qt的安裝目錄指定文件夾下,這樣就當作了qt自己的文件來使用了。

3.1.h文件拷貝

在qt的安裝目錄include文件夾下(如D:\Qt\Qt5.6.3_2013\5.6.3\msvc2013\include),創建文件夾QtMqtt,並將文件夾qmqtt-master\src\mqtt下的.h文件拷貝到QtMqtt文件夾下。

​​​​​​​3.2Lib和dll文件拷貝

Lib文件:將Qt5Qmqtt.lib和Qt5Qmqttd.lib文件拷貝到qt的安裝目錄的lib文件夾下(如D:\Qt\Qt5.6.3_2013\5.6.3\msvc2013\lib)。

Dll文件:將Qt5Qmqtt.dll和Qt5Qmqttd.dll文件拷貝到qt的安裝目錄的bin文件夾下(如D:\Qt\Qt5.6.3_2013\5.6.3\msvc2013\bin)。

3.3調用方法

在vs2013工程--右鍵--屬性,C/C++--常規--附加包含目錄,添加$(QTDIR)\include\QtMqtt;鏈接器--輸入--附加依賴項,添加$(QTDIR)\lib\Qt5Qmqttd.lib(Release爲$(QTDIR)\lib\Qt5Qmqtt.lib)。在使用時,#include <qmqtt.h>即可。

4.Demo演示

關鍵方法:

m_client = new QMQTT::Client(QHostAddress(ip), port, this);

m_client->setUsername(Username);

m_client->setPassword(Password);

m_client->setClientId(clientid);

m_client->connectToHost();

 

//m_client->setAutoReconnect(true);

 

connect(m_client, &QMQTT::Client::connected, this, [this]() {

const QString content = QLatin1String(" connected");

});

connect(m_client, &QMQTT::Client::disconnected, this, [this]() {

const QString content = QLatin1String(" disconnected");

});

 

connect(m_client, &QMQTT::Client::received, this, [this](const QMQTT::Message& message) {

const QString content = QString("received, Topic: %1, Message: %2").arg(message.topic()).arg(QString(message.payload()));

    });

 

connect(m_client, &QMQTT::Client::pingresp, this, [this]() {

        const QString content = QLatin1String(" pingresp");

    });

connect(m_client, &QMQTT::Client::subscribed, this, [this](const QString& topic, const quint8 qos) {

const QString content = QString("subscribed, Topic: %1, qos: %2").arg(topic).arg(qos);

});

connect(m_client, &QMQTT::Client::unsubscribed, this, [this](const QString& topic) {

const QString content = QString("unsubscribed, Topic: %1").arg(topic);

});

connect(m_client, &QMQTT::Client::published, this, [this](const QMQTT::Message& message, quint16 msgid) {

const QString content = QString("published, Topic: %1, Message: %2, msgid:%3").arg(message.topic()).arg(QString(message.payload())).arg(msgid);

});

connect(m_client, &QMQTT::Client::error, this, [this](const QMQTT::ClientError error) {

const QString content = QString("error, value: %1").arg(error);

});

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章