Qt使用qmqtt

1.qmqtt是一个Qt的MQTT客户端协议库,可以进行mqtt客户端的开发,下载地址是:https://github.com/emqx/qmqtt

 2.下载出来的是源码,使用的话需要自己编译,请使用qt5.3及以上版本编译,在windows平台的话还得指定CONFIG += NO_UNIT_TESTS;如果要支持websocket的话请使用qt5.7及以上版本,同时需要配置CONFIG += QMQTT_WEBSOCKETS

 3.打开工程文件,选择src执行qmake,然后点击构建即可生成相应的库文件

 

.

4.将四个库文件和所有的头文件整理到新建的两个lib和include件夹中如下

 

 

 

 5.新建qt工程hellomqtt,将上一步建立的两个文件夹拷贝到新的工程目录下,并在qt中添加qmqtt库

 6.程序代码见下

《1》hellomqtt.pro文件

#-------------------------------------------------
#
# Project created by QtCreator 2019-08-06T22:00:37
#
#-------------------------------------------------

QT       += core gui network
CONFIG += c++11

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = hellomqtt
TEMPLATE = app

# The following define makes your compiler emit warnings if you use
# any feature of Qt which as been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0


SOURCES += 
        main.cpp 
        mainwindow.cpp

HEADERS += 
        mainwindow.h

FORMS += 
        mainwindow.ui

win32:CONFIG(release, debug|release): LIBS += -L$$PWD/lib/ -lqmqtt
else:win32:CONFIG(debug, debug|release): LIBS += -L$$PWD/lib/ -lqmqttd

INCLUDEPATH += $$PWD/include
DEPENDPATH += $$PWD/include

win32-g++:CONFIG(release, debug|release): PRE_TARGETDEPS += $$PWD/lib/libqmqtt.a
else:win32-g++:CONFIG(debug, debug|release): PRE_TARGETDEPS += $$PWD/lib/libqmqttd.a
else:win32:!win32-g++:CONFIG(release, debug|release): PRE_TARGETDEPS += $$PWD/lib/qmqtt.lib
else:win32:!win32-g++:CONFIG(debug, debug|release): PRE_TARGETDEPS += $$PWD/lib/qmqttd.lib

《2》mainwindow.h文件

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include "qmqtt.h"
#include<QDebug>
using namespace QMQTT;

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void on_pb_connect_clicked();

    void on_pushButton_clicked();

    void on_pushButton_2_clicked();

    void on_pushButton_3_clicked();

private:
    Ui::MainWindow *ui;
    QMQTT::Client *client; //MQTT客户端指针

public slots:
    void doConnected();  //MQTT 连接成功
    void doDisconnected();//MQTT连接断开
    void doDataReceived(QMQTT::Message);//MQTT收到数据
};

#endif // MAINWINDOW_H

《3》mainwindow.cpp文件

  1 #include "mainwindow.h"
  2 #include "ui_mainwindow.h"
  3 
  4 #include<qnetwork.h>
  5 
  6 MainWindow::MainWindow(QWidget *parent) :
  7     QMainWindow(parent),
  8     ui(new Ui::MainWindow)
  9 {
 10     ui->setupUi(this);
 11    // QMQTT::Client *client = new QMQTT::Client(QHostAddress::LocalHost,11883);
 12    //client = new QMQTT::Client(QHostAddress("127.0.0.1"),11883);//emqtt测试服务器
 13     client = new QMQTT::Client(QHostAddress("192.168.1.10"),1883);
 14     client->setClientId("clientid");
 15     client->setUsername("user");
 16     client->setPassword("password");
 17     ui->pushButton->setEnabled(false);
 18     ui->pushButton_2->setEnabled(false);
 19     connect(client,SIGNAL(connected()),this,SLOT(doConnected()));
 20     connect(client,SIGNAL(disconnected()),this,SLOT(doDisconnected()));
 21     connect(client,SIGNAL(received(QMQTT::Message)),this,SLOT(doDataReceived(QMQTT::Message)));
 22 
 23 }
 24 
 25 MainWindow::~MainWindow()
 26 {
 27     delete ui;
 28 }
 29 
 30 void MainWindow::on_pb_connect_clicked()
 31 {
 32 
 33     if(!client->isConnectedToHost())
 34     {
 35         client->connectToHost();
 36     }
 37     else {
 38         client->disconnectFromHost();
 39     }
 40 
 41 }
 42 
 43 void MainWindow::doConnected()
 44 {
 45     ui->rb_status->setChecked(true);
 46     ui->pb_connect->setText("Disconnect");
 47     ui->pushButton->setEnabled(true);
 48     ui->pushButton_2->setEnabled(true);
 49 }
 50 
 51 void MainWindow::doDisconnected()
 52 {
 53     ui->rb_status->setChecked(false);
 54     ui->pb_connect->setText("Connect");
 55     ui->pushButton->setEnabled(false);
 56     ui->pushButton_2->setEnabled(false);
 57 }
 58 
 59 void MainWindow::doDataReceived(Message message)
 60 {
 61     QString mes = QString(message.id())+" "+QString(message.qos())+" "+message.topic()+" "+message.payload()+"
";
 62     ui->te_log->append(mes);
 63 }
 64 
 65 
 66 void MainWindow::on_pushButton_clicked()
 67 {
 68     QString topic = ui->le_pb_topic->text().trimmed();
 69     QString payload = ui->le_pu_payload->text().trimmed();
 70     if(topic.isEmpty() || payload.isEmpty())
 71     {
 72         qDebug()<<"pub topic and payload is empty!"<<endl;
 73         return;
 74     }
 75     QMQTT::Message message(136,topic,payload.toUtf8());
 76 
 77     client->publish(message);
 78 }
 79 
 80 void MainWindow::on_pushButton_2_clicked()
 81 {
 82     QString topic = ui->le_sub_topic->text().trimmed();
 83     if(topic.isEmpty())
 84     {
 85         qDebug()<<"sub topic and payload is empty!"<<endl;
 86         return;
 87     }
 88     qDebug()<<topic<<endl;
 89     client->subscribe(topic);
 90 }
 91 
 92 void MainWindow::on_pushButton_3_clicked()
 93 {
 94     QString topic = ui->le_sub_topic->text().trimmed();
 95     if(topic.isEmpty())
 96     {
 97         qDebug()<<"sub topic and payload is empty!"<<endl;
 98         return;
 99     }
100     client->unsubscribe(topic);
101 
102 }

《4》main.cpp文件

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

《5》mainwindow.ui文件

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>400</width>
    <height>300</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralWidget">
   <layout class="QVBoxLayout" name="verticalLayout_3">
    <item>
     <layout class="QHBoxLayout" name="horizontalLayout_5">
      <item>
       <widget class="QRadioButton" name="rb_status">
        <property name="text">
         <string>连接状态</string>
        </property>
       </widget>
      </item>
      <item>
       <widget class="QPushButton" name="pb_connect">
        <property name="text">
         <string>Connect</string>
        </property>
       </widget>
      </item>
     </layout>
    </item>
    <item>
     <layout class="QHBoxLayout" name="horizontalLayout_3">
      <item>
       <layout class="QVBoxLayout" name="verticalLayout">
        <item>
         <layout class="QHBoxLayout" name="horizontalLayout">
          <item>
           <widget class="QLabel" name="label">
            <property name="text">
             <string>Topic:</string>
            </property>
           </widget>
          </item>
          <item>
           <widget class="QLineEdit" name="le_pb_topic"/>
          </item>
         </layout>
        </item>
        <item>
         <layout class="QHBoxLayout" name="horizontalLayout_2">
          <item>
           <widget class="QLabel" name="label_2">
            <property name="text">
             <string>Payload:</string>
            </property>
           </widget>
          </item>
          <item>
           <widget class="QLineEdit" name="le_pu_payload"/>
          </item>
         </layout>
        </item>
       </layout>
      </item>
      <item>
       <widget class="QPushButton" name="pushButton">
        <property name="text">
         <string>Publish</string>
        </property>
       </widget>
      </item>
     </layout>
    </item>
    <item>
     <layout class="QHBoxLayout" name="horizontalLayout_4">
      <item>
       <widget class="QLabel" name="label_3">
        <property name="text">
         <string>Topic:</string>
        </property>
       </widget>
      </item>
      <item>
       <widget class="QLineEdit" name="le_sub_topic"/>
      </item>
      <item>
       <widget class="QPushButton" name="pushButton_2">
        <property name="text">
         <string>Subscribe</string>
        </property>
       </widget>
      </item>
      <item>
       <widget class="QPushButton" name="pushButton_3">
        <property name="text">
         <string>UnSubscribe</string>
        </property>
       </widget>
      </item>
     </layout>
    </item>
    <item>
     <layout class="QVBoxLayout" name="verticalLayout_2">
      <item>
       <widget class="QLabel" name="label_4">
        <property name="text">
         <string>LOG:</string>
        </property>
       </widget>
      </item>
      <item>
       <widget class="QTextBrowser" name="te_log"/>
      </item>
     </layout>
    </item>
   </layout>
  </widget>
  <widget class="QMenuBar" name="menuBar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>400</width>
     <height>23</height>
    </rect>
   </property>
  </widget>
  <widget class="QToolBar" name="mainToolBar">
   <attribute name="toolBarArea">
    <enum>TopToolBarArea</enum>
   </attribute>
   <attribute name="toolBarBreak">
    <bool>false</bool>
   </attribute>
  </widget>
  <widget class="QStatusBar" name="statusBar"/>
 </widget>
 <layoutdefault spacing="6" margin="11"/>
 <resources/>
 <connections/>
</ui>

7.编译和运行程序,经过测试,可以实现发布和订阅主题

 欢迎加入C和C++交流群:

原文地址:https://www.cnblogs.com/huipengbo/p/12082935.html