文件目录
.pro文件需加此依赖,并且需要用msvc编译器 这个用的是2017 32bit
QT += bluetooth
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QListWidgetItem>
#include <QtBluetooth/qbluetoothglobal.h>
#include <QtBluetooth/qbluetoothlocaldevice.h>
#include <qbluetoothaddress.h>
#include <qbluetoothdevicediscoveryagent.h>
#include <qbluetoothlocaldevice.h>
#include <qbluetoothsocket.h>
#define MAX_LENGTH 256
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = nullptr);
~Widget();
private slots:
void on_pushButton_scan_clicked();
void addBlueToothDevicesToList(const QBluetoothDeviceInfo&);
void on_pushButton_openBluetooth_clicked();
void on_pushButton_closeDevice_clicked();
void itemActivated(QListWidgetItem *item);
void readBluetoothDataEvent();
void bluetoothConnectedEvent();
void bluetoothDisconnectedEvent();
void on_pushButton_disconnect_clicked();
void on_pushButton_send_clicked();
void on_pushButton_clear_clicked();
private:
Ui::Widget *ui;
// 用来对周围蓝牙进行搜寻
QBluetoothDeviceDiscoveryAgent *discoveryAgent;
// 对本地设备进行操作
QBluetoothLocalDevice *localDevice;
// 进行蓝牙配对链接和数据传输
QBluetoothSocket *socket;
unsigned char comBuffer[15];
unsigned int comCount;
QString comStr;
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include "QMessageBox"
static const QLatin1String serviceUuid("00001101-0000-1000-8000-00805F9B34FB");
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
discoveryAgent = new QBluetoothDeviceDiscoveryAgent();
localDevice = new QBluetoothLocalDevice();
socket = new QBluetoothSocket(QBluetoothServiceInfo::RfcommProtocol);
// 蓝牙进行查找
connect(discoveryAgent,
SIGNAL(deviceDiscovered(QBluetoothDeviceInfo)),
this,
SLOT(addBlueToothDevicesToList(QBluetoothDeviceInfo))
);
connect(ui->list,
SIGNAL(itemActivated(QListWidgetItem*)),
this,
SLOT(itemActivated(QListWidgetItem*))
);
connect(socket,
SIGNAL(readyRead()),
this,
SLOT(readBluetoothDataEvent())
);
connect(socket,
SIGNAL(connected()),
this,
SLOT(bluetoothConnectedEvent())
);
connect(socket,
SIGNAL(disconnected()),
this,
SLOT(bluetoothDisconnectedEvent())
);
// 对本地设备模式进行判断
if( localDevice->hostMode() == QBluetoothLocalDevice::HostPoweredOff ) {
ui->pushButton_openBluetooth->setEnabled(true);
ui->pushButton_closeDevice->setEnabled(false);
}else {
ui->pushButton_openBluetooth->setEnabled(false);
ui->pushButton_closeDevice->setEnabled(true);
}
// 蓝牙可见
if( localDevice->hostMode() == QBluetoothLocalDevice::HostDiscoverable ) {
ui->checkBox_discoverable->setChecked(true);
}else {
ui->checkBox_discoverable->setChecked(false);
}
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_pushButton_scan_clicked()
{
discoveryAgent->start();
ui->pushButton_scan->setEnabled(false);
}
// 将搜索的蓝牙显示在界面
void Widget::addBlueToothDevicesToList( const QBluetoothDeviceInfo &info )
{
// %1为蓝牙设备的地址,%2为蓝牙设备的名字
QString label = QString("%1 %2").arg(info.address().toString()).arg(info.name());
QList<QListWidgetItem *> items = ui->list->findItems(label, Qt::MatchExactly);
if (items.empty()) {
QListWidgetItem *item = new QListWidgetItem(label);
QBluetoothLocalDevice::Pairing pairingStatus = localDevice->pairingStatus(info.address());
// 蓝牙状态pairingStatus,Pairing枚举类型 0:Unpaired没配对 1:Paired配对但没授权 2:AuthorizedPaired配对且授权
if (pairingStatus == QBluetoothLocalDevice::Paired || pairingStatus == QBluetoothLocalDevice::AuthorizedPaired )
item->setTextColor(QColor(Qt::green));
else
item->setTextColor(QColor(Qt::black));
// 输出显示
ui->list->addItem(item);
}
}
// open按钮的槽函数
void Widget::on_pushButton_openBluetooth_clicked()
{
localDevice->powerOn();
ui->pushButton_closeDevice->setEnabled(true);
ui->pushButton_openBluetooth->setEnabled(false);
ui->pushButton_scan->setEnabled(true);
}
// close按钮的槽函数
void Widget::on_pushButton_closeDevice_clicked()
{
localDevice->setHostMode(QBluetoothLocalDevice::HostPoweredOff);
ui->pushButton_closeDevice->setEnabled(false);
ui->pushButton_openBluetooth->setEnabled(true);
ui->pushButton_scan->setEnabled(false);
}
//
void Widget::itemActivated(QListWidgetItem *item)
{
QString text = item->text();
int index = text.indexOf(' ');
if (index == -1)
return;
QBluetoothAddress address(text.left(index));
QString name(text.mid(index + 1));
qDebug() << "You has choice the bluetooth address is " << address;
qDebug() << "The device is connneting.... ";
QMessageBox::information(this,tr("Info"),tr("The device is connecting..."));
socket->connectToService(address, QBluetoothUuid(serviceUuid) ,QIODevice::ReadWrite);
}
// 读取数据
void Widget::readBluetoothDataEvent()
{
QByteArray line = socket->readAll();
QString strData = line.toHex();
comStr.append(strData);
qDebug() <<"rec data is: "<< comStr;
qDebug() <<"The comStr length is: " << comStr.length();
if(comStr.length() >= 30) {
ui->textBrowser_info->append(comStr + "\n");
comStr.clear();
}
}
// 选择的蓝牙设备进行链接
void Widget::bluetoothConnectedEvent()
{
qDebug() << "The android device has been connected successfully!";
QMessageBox::information(this,tr("Info"),tr("successful connection!"));
}
// 断开连接
void Widget::bluetoothDisconnectedEvent()
{
qDebug() << "The android device has been disconnected successfully!";
QMessageBox::information(this,tr("Info"),tr("successful disconnection!"));
}
// 断开连接函数
void Widget::on_pushButton_disconnect_clicked()
{
socket->disconnectFromService();
}
// 发送信息
void Widget::on_pushButton_send_clicked()
{
QByteArray arrayData;
QString s("Hello Windows!!!\nThis message is sended via bluetooth of android device!\n");
arrayData = s.toUtf8();
socket->write(arrayData);
}
void Widget::on_pushButton_clear_clicked()
{
ui->textBrowser_info->clear();
}