image.png

    文件目录
    image.png

    .pro文件需加此依赖,并且需要用msvc编译器 这个用的是2017 32bit

    1. QT += bluetooth

    widget.h

    1. #ifndef WIDGET_H
    2. #define WIDGET_H
    3. #include <QWidget>
    4. #include <QListWidgetItem>
    5. #include <QtBluetooth/qbluetoothglobal.h>
    6. #include <QtBluetooth/qbluetoothlocaldevice.h>
    7. #include <qbluetoothaddress.h>
    8. #include <qbluetoothdevicediscoveryagent.h>
    9. #include <qbluetoothlocaldevice.h>
    10. #include <qbluetoothsocket.h>
    11. #define MAX_LENGTH 256
    12. namespace Ui {
    13. class Widget;
    14. }
    15. class Widget : public QWidget
    16. {
    17. Q_OBJECT
    18. public:
    19. explicit Widget(QWidget *parent = nullptr);
    20. ~Widget();
    21. private slots:
    22. void on_pushButton_scan_clicked();
    23. void addBlueToothDevicesToList(const QBluetoothDeviceInfo&);
    24. void on_pushButton_openBluetooth_clicked();
    25. void on_pushButton_closeDevice_clicked();
    26. void itemActivated(QListWidgetItem *item);
    27. void readBluetoothDataEvent();
    28. void bluetoothConnectedEvent();
    29. void bluetoothDisconnectedEvent();
    30. void on_pushButton_disconnect_clicked();
    31. void on_pushButton_send_clicked();
    32. void on_pushButton_clear_clicked();
    33. private:
    34. Ui::Widget *ui;
    35. // 用来对周围蓝牙进行搜寻
    36. QBluetoothDeviceDiscoveryAgent *discoveryAgent;
    37. // 对本地设备进行操作
    38. QBluetoothLocalDevice *localDevice;
    39. // 进行蓝牙配对链接和数据传输
    40. QBluetoothSocket *socket;
    41. unsigned char comBuffer[15];
    42. unsigned int comCount;
    43. QString comStr;
    44. };
    45. #endif // WIDGET_H

    widget.cpp

    1. #include "widget.h"
    2. #include "ui_widget.h"
    3. #include "QMessageBox"
    4. static const QLatin1String serviceUuid("00001101-0000-1000-8000-00805F9B34FB");
    5. Widget::Widget(QWidget *parent) :
    6. QWidget(parent),
    7. ui(new Ui::Widget)
    8. {
    9. ui->setupUi(this);
    10. discoveryAgent = new QBluetoothDeviceDiscoveryAgent();
    11. localDevice = new QBluetoothLocalDevice();
    12. socket = new QBluetoothSocket(QBluetoothServiceInfo::RfcommProtocol);
    13. // 蓝牙进行查找
    14. connect(discoveryAgent,
    15. SIGNAL(deviceDiscovered(QBluetoothDeviceInfo)),
    16. this,
    17. SLOT(addBlueToothDevicesToList(QBluetoothDeviceInfo))
    18. );
    19. connect(ui->list,
    20. SIGNAL(itemActivated(QListWidgetItem*)),
    21. this,
    22. SLOT(itemActivated(QListWidgetItem*))
    23. );
    24. connect(socket,
    25. SIGNAL(readyRead()),
    26. this,
    27. SLOT(readBluetoothDataEvent())
    28. );
    29. connect(socket,
    30. SIGNAL(connected()),
    31. this,
    32. SLOT(bluetoothConnectedEvent())
    33. );
    34. connect(socket,
    35. SIGNAL(disconnected()),
    36. this,
    37. SLOT(bluetoothDisconnectedEvent())
    38. );
    39. // 对本地设备模式进行判断
    40. if( localDevice->hostMode() == QBluetoothLocalDevice::HostPoweredOff ) {
    41. ui->pushButton_openBluetooth->setEnabled(true);
    42. ui->pushButton_closeDevice->setEnabled(false);
    43. }else {
    44. ui->pushButton_openBluetooth->setEnabled(false);
    45. ui->pushButton_closeDevice->setEnabled(true);
    46. }
    47. // 蓝牙可见
    48. if( localDevice->hostMode() == QBluetoothLocalDevice::HostDiscoverable ) {
    49. ui->checkBox_discoverable->setChecked(true);
    50. }else {
    51. ui->checkBox_discoverable->setChecked(false);
    52. }
    53. }
    54. Widget::~Widget()
    55. {
    56. delete ui;
    57. }
    58. void Widget::on_pushButton_scan_clicked()
    59. {
    60. discoveryAgent->start();
    61. ui->pushButton_scan->setEnabled(false);
    62. }
    63. // 将搜索的蓝牙显示在界面
    64. void Widget::addBlueToothDevicesToList( const QBluetoothDeviceInfo &info )
    65. {
    66. // %1为蓝牙设备的地址,%2为蓝牙设备的名字
    67. QString label = QString("%1 %2").arg(info.address().toString()).arg(info.name());
    68. QList<QListWidgetItem *> items = ui->list->findItems(label, Qt::MatchExactly);
    69. if (items.empty()) {
    70. QListWidgetItem *item = new QListWidgetItem(label);
    71. QBluetoothLocalDevice::Pairing pairingStatus = localDevice->pairingStatus(info.address());
    72. // 蓝牙状态pairingStatus,Pairing枚举类型 0:Unpaired没配对 1:Paired配对但没授权 2:AuthorizedPaired配对且授权
    73. if (pairingStatus == QBluetoothLocalDevice::Paired || pairingStatus == QBluetoothLocalDevice::AuthorizedPaired )
    74. item->setTextColor(QColor(Qt::green));
    75. else
    76. item->setTextColor(QColor(Qt::black));
    77. // 输出显示
    78. ui->list->addItem(item);
    79. }
    80. }
    81. // open按钮的槽函数
    82. void Widget::on_pushButton_openBluetooth_clicked()
    83. {
    84. localDevice->powerOn();
    85. ui->pushButton_closeDevice->setEnabled(true);
    86. ui->pushButton_openBluetooth->setEnabled(false);
    87. ui->pushButton_scan->setEnabled(true);
    88. }
    89. // close按钮的槽函数
    90. void Widget::on_pushButton_closeDevice_clicked()
    91. {
    92. localDevice->setHostMode(QBluetoothLocalDevice::HostPoweredOff);
    93. ui->pushButton_closeDevice->setEnabled(false);
    94. ui->pushButton_openBluetooth->setEnabled(true);
    95. ui->pushButton_scan->setEnabled(false);
    96. }
    97. //
    98. void Widget::itemActivated(QListWidgetItem *item)
    99. {
    100. QString text = item->text();
    101. int index = text.indexOf(' ');
    102. if (index == -1)
    103. return;
    104. QBluetoothAddress address(text.left(index));
    105. QString name(text.mid(index + 1));
    106. qDebug() << "You has choice the bluetooth address is " << address;
    107. qDebug() << "The device is connneting.... ";
    108. QMessageBox::information(this,tr("Info"),tr("The device is connecting..."));
    109. socket->connectToService(address, QBluetoothUuid(serviceUuid) ,QIODevice::ReadWrite);
    110. }
    111. // 读取数据
    112. void Widget::readBluetoothDataEvent()
    113. {
    114. QByteArray line = socket->readAll();
    115. QString strData = line.toHex();
    116. comStr.append(strData);
    117. qDebug() <<"rec data is: "<< comStr;
    118. qDebug() <<"The comStr length is: " << comStr.length();
    119. if(comStr.length() >= 30) {
    120. ui->textBrowser_info->append(comStr + "\n");
    121. comStr.clear();
    122. }
    123. }
    124. // 选择的蓝牙设备进行链接
    125. void Widget::bluetoothConnectedEvent()
    126. {
    127. qDebug() << "The android device has been connected successfully!";
    128. QMessageBox::information(this,tr("Info"),tr("successful connection!"));
    129. }
    130. // 断开连接
    131. void Widget::bluetoothDisconnectedEvent()
    132. {
    133. qDebug() << "The android device has been disconnected successfully!";
    134. QMessageBox::information(this,tr("Info"),tr("successful disconnection!"));
    135. }
    136. // 断开连接函数
    137. void Widget::on_pushButton_disconnect_clicked()
    138. {
    139. socket->disconnectFromService();
    140. }
    141. // 发送信息
    142. void Widget::on_pushButton_send_clicked()
    143. {
    144. QByteArray arrayData;
    145. QString s("Hello Windows!!!\nThis message is sended via bluetooth of android device!\n");
    146. arrayData = s.toUtf8();
    147. socket->write(arrayData);
    148. }
    149. void Widget::on_pushButton_clear_clicked()
    150. {
    151. ui->textBrowser_info->clear();
    152. }

    参考文章:https://www.cnblogs.com/sigma0/p/5769527.html

    文件:
    QT_Bluetooth_An.zip