Qt/C++ 获取 QBluetoothLocalDevice 列表

Qt/C++ Get list of QBluetoothLocalDevice

在我的设备上连接了多个蓝牙适配器。就我而言,我想获取有关连接到第二个适配器的设备的一些信息(专门调用 pairingStatus())。为此,我需要获取提供此信息的 QBluetoothLocalDevice 实例。问题是当我知道适配器的地址时无法构造实例:

QBluetoothLocalDevice BluetoothConnector::getBluetoothAdapter()
{
    QList<QBluetoothHostInfo> adapters = QBluetoothLocalDevice::allDevices();
    QBluetoothLocalDevice device = QBluetoothLocalDevice(QBluetoothAddress());
    if(adapters.size() >= 2)
    {
        device = QBluetoothLocalDevice(adapters.at(1).address());
    }
    return device;
}

这是因为构造函数是显式声明的。如何构建或获取作为第二个适配器的 QBluetoothLocalDevice?

您对问题的描述有点不清楚(例如,声明了哪个构造函数 explicit?)但是显示的代码无法编译,因为它试图分配一个 QBluetoothLocalDevice 继承自 QObject 因此不是 assignable/copyable.

相反,您可能应该 return 一个指向新创建的 QBluetoothLocalDevice 的智能指针,让调用者决定如何处理它...

std::unique_ptr<QBluetoothLocalDevice> BluetoothConnector::getBluetoothAdapter ()
{
    auto adapters = QBluetoothLocalDevice::allDevices();
    if (adapters.size() >= 2)
        return std::make_unique<QBluetoothLocalDevice>(adapters.at(1).address());

    /*
     * No adaptor found so throw an exception.  You may want to return
     * a default constructed std::unique_ptr instead.
     */
    throw std::out_of_range("no adaptor found");
}

顺便说一句,您的 BluetoothConnector::getBluetoothAdapter 实现似乎没有修改任何成员变量,因此应该 const 合格。