Qt 开发之蓝牙连接

在Qt开发中,你可以通过QBluetoothDeviceDiscoveryAgent来搜索蓝牙设备,并将搜索到的设备显示在一个列表中。每个设备后面可以添加一个“连接”按钮,用户点击按钮后可以连接到对应的蓝牙设备。

以下是一个完整的示例,展示如何实现这一功能:


1. 项目结构

  • 创建一个Qt Widgets应用程序。
  • 使用QListWidgetQTableWidget来显示蓝牙设备列表。
  • 为每个设备添加一个“连接”按钮。

2. 代码实现

2.1 在.pro文件中添加蓝牙模块
QT += bluetooth widgets
2.2 主窗口实现
#include <QWidget>
#include <QVBoxLayout>
#include <QListWidget>
#include <QPushButton>
#include <QBluetoothDeviceDiscoveryAgent>
#include <QBluetoothDeviceInfo>
#include <QBluetoothSocket>
#include <QDebug>

class BluetoothDeviceItem : public QWidget
{
    Q_OBJECT

public:
    BluetoothDeviceItem(const QBluetoothDeviceInfo &deviceInfo, QWidget *parent = nullptr)
        : QWidget(parent), m_deviceInfo(deviceInfo)
    {
        QHBoxLayout *layout = new QHBoxLayout(this);

        // 显示设备名称和地址
        QString deviceText = QString("%1 (%2)").arg(deviceInfo.name()).arg(deviceInfo.address().toString());
        QLabel *label = new QLabel(deviceText, this);
        layout->addWidget(label);

        // 添加连接按钮
        QPushButton *connectButton = new QPushButton("连接", this);
        connect(connectButton, &QPushButton::clicked, this, &BluetoothDeviceItem::onConnectClicked);
        layout->addWidget(connectButton);

        setLayout(layout);
    }

private slots:
    void onConnectClicked()
    {
        qDebug() << "Connecting to:" << m_deviceInfo.name() << m_deviceInfo.address().toString();

        // 创建蓝牙套接字并连接到设备
        QBluetoothSocket *socket = new QBluetoothSocket(QBluetoothServiceInfo::RfcommProtocol, this);
        connect(socket, &QBluetoothSocket::connected, this, [=]() {
            qDebug() << "Connected to device:" << m_deviceInfo.name();
        });
        connect(socket, &QBluetoothSocket::disconnected, this, [=]() {
            qDebug() << "Disconnected from device:" << m_deviceInfo.name();
        });
        connect(socket, QOverload<QBluetoothSocket::SocketError>::of(&QBluetoothSocket::error), this, [=](QBluetoothSocket::SocketError error) {
            qDebug() << "Socket error:" << error;
        });

        // 连接到设备的RFCOMM服务
        socket->connectToService(m_deviceInfo.address(), QBluetoothUuid::SerialPort);
    }

private:
    QBluetoothDeviceInfo m_deviceInfo;
};

class BluetoothDiscoveryWidget : public QWidget
{
    Q_OBJECT

public:
    BluetoothDiscoveryWidget(QWidget *parent = nullptr)
        : QWidget(parent)
    {
        QVBoxLayout *layout = new QVBoxLayout(this);

        // 设备列表
        m_deviceList = new QListWidget(this);
        layout->addWidget(m_deviceList);

        // 开始搜索按钮
        QPushButton *startScanButton = new QPushButton("开始搜索", this);
        connect(startScanButton, &QPushButton::clicked, this, &BluetoothDiscoveryWidget::startDiscovery);
        layout->addWidget(startScanButton);

        setLayout(layout);
    }

private slots:
    void startDiscovery()
    {
        // 清空设备列表
        m_deviceList->clear();

        // 创建设备发现代理
        m_discoveryAgent = new QBluetoothDeviceDiscoveryAgent(this);
        connect(m_discoveryAgent, &QBluetoothDeviceDiscoveryAgent::deviceDiscovered, this, &BluetoothDiscoveryWidget::deviceDiscovered);
        connect(m_discoveryAgent, QOverload<QBluetoothDeviceDiscoveryAgent::Error>::of(&QBluetoothDeviceDiscoveryAgent::error), this, &BluetoothDiscoveryWidget::deviceScanError);
        connect(m_discoveryAgent, &QBluetoothDeviceDiscoveryAgent::finished, this, &BluetoothDiscoveryWidget::deviceScanFinished);

        // 开始搜索
        m_discoveryAgent->start();
    }

    void deviceDiscovered(const QBluetoothDeviceInfo &deviceInfo)
    {
        // 为每个设备创建一个自定义的设备项
        BluetoothDeviceItem *itemWidget = new BluetoothDeviceItem(deviceInfo, this);
        QListWidgetItem *listItem = new QListWidgetItem(m_deviceList);
        m_deviceList->setItemWidget(listItem, itemWidget);
        listItem->setSizeHint(itemWidget->sizeHint());
    }

    void deviceScanError(QBluetoothDeviceDiscoveryAgent::Error error)
    {
        qDebug() << "Scan error:" << error;
    }

    void deviceScanFinished()
    {
        qDebug() << "Scan finished";
    }

private:
    QBluetoothDeviceDiscoveryAgent *m_discoveryAgent = nullptr;
    QListWidget *m_deviceList = nullptr;
};

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    BluetoothDiscoveryWidget widget;
    widget.show();

    return app.exec();
}

#include "main.moc"

3. 代码说明

3.1 BluetoothDeviceItem
  • 这是一个自定义的QWidget,用于显示每个蓝牙设备的名称和地址。
  • 每个设备后面都有一个“连接”按钮,点击按钮后会尝试连接到该设备。
3.2 BluetoothDiscoveryWidget
  • 这是主窗口,包含一个设备列表和一个“开始搜索”按钮。
  • 点击“开始搜索”按钮后,会调用QBluetoothDeviceDiscoveryAgent来搜索附近的蓝牙设备。
  • 搜索到的设备会显示在列表中,每个设备后面都有一个“连接”按钮。
3.3 连接逻辑
  • 当用户点击“连接”按钮时,会创建一个QBluetoothSocket,并尝试连接到设备的RFCOMM服务。
  • 连接成功或失败时会输出相应的日志。

4. 运行效果

  1. 运行程序后,点击“开始搜索”按钮,程序会搜索附近的蓝牙设备。
  2. 搜索完成后,设备列表中会显示设备的名称和地址,每个设备后面都有一个“连接”按钮。
  3. 点击“连接”按钮,程序会尝试连接到对应的蓝牙设备。

5. 注意事项

  • 权限:在Android或iOS上运行时,确保应用程序具有蓝牙权限。
  • 平台差异:在某些平台上(如Linux),可能需要额外的配置才能使用蓝牙功能。
  • RFCOMM服务:连接时使用的是QBluetoothUuid::SerialPort,这是标准的RFCOMM服务UUID。如果设备使用其他服务,需要根据实际情况修改UUID。

通过以上代码,你可以轻松实现一个蓝牙设备搜索和连接的界面。

Qt for Android中连接BLE蓝牙设备,你需要使用Qt蓝牙库和相关类。根据你提供的引用内容,我可以看到你已经参考了一些文章和博客,并找到了一个功能相近的项目。 首先,你需要包含以下头文件: #include <QtBluetooth/qbluetoothlocaldevice.h> // 本地设备信息 #include <QBluetoothDeviceDiscoveryAgent> // 设备搜寻 #include <QBluetoothDeviceInfo> // 设备信息 #include <QLowEnergyController> // 设备连接 #include <QLowEnergyService> // 数据接收、发送 \[3\] 然后,你可以使用QLowEnergyController类来连接BLE设备。你可以使用QBluetoothDeviceDiscoveryAgent类来搜索附近的设备,并获取设备信息。一旦你找到了目标设备,你可以使用QLowEnergyController类来连接设备。 在连接设备之前,你可以使用QListWidget控件来显示设备列表,并使用双击或按钮来触发连接设备的操作。你可以使用connect函数来连接信号和槽函数,以便在用户双击设备列表项或点击按钮时触发连接操作。 connect(ui->Device_List, SIGNAL(itemActivated(QListWidgetItem*)),this, SLOT(connect_Device())); //连接设备 connect(ui->Link_Device,&QPushButton::clicked,\[=\]{ connect_Device(); }); //连接设备 connect(ui->disLink_Device,&QPushButton::clicked,\[=\]{ m_pcontrol->disconnectFromDevice(); ui->Server_List->clear(); }); //断开设备连接 \[2\] 需要注意的是,Qt官方的蓝牙套接字只适用于SPP传输的蓝牙,而BLE蓝牙需要使用QLowEnergyController和QLowEnergyService类来实现连接和数据传输。这可能会比蓝牙套接字复杂很多倍。 希望这些信息对你有帮助,祝你成功完成你的毕设! #### 引用[.reference_title] - *1* [Qt for Android 使用BLE串口蓝牙发送数据](https://blog.youkuaiyun.com/qq_35342292/article/details/104170372)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [QT for Android BLE Bluetooch QT BLE](https://blog.youkuaiyun.com/qq_27620407/article/details/129122512)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飘飘燃雪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值