注意:我最初的帖子有一个重要的遗漏:我遗漏了在main的开头已经实例化了主QApplication实例。创建两个QApplication实例是导致问题的原因。使用相同的QApplication实例而不是创建两个实例解决了此问题。
我的目的是在主应用程序之前运行一个QApplication,以迭代可用的蓝牙设备,找到一个特定的设备。如果在一定时间内找不到具体的QApplication,则会被销毁。QApplication::exec()一被调用,第一个存储的lambda (startDiscovery)就会被调用,但是第二个存储的lambda (cancelDiscovery)永远不会被调用!相关部分如下:
#include <QtBluetooth/QBluetoothDeviceInfo>
#include <QtBluetooth/QBluetoothDeviceDiscoveryAgent>
#include <QtBluetooth/QBluetoothLocalDevice>
#include <QTimer>
#include <QString>
#include <QApplication>
#include <memory>
#define TARGET_BLUETOOTH_DEVICE_NAME "MyBluetoothDevice"
#define BLUETOOTH_DISCOVERY_TIMEOUT 5000 //5 second timeout
int main(int argc, char *argv[])
{
std::shared_ptr<QApplication> mainApplication{std::make_shared<QApplication>(argc, argv)};
//Error checking for no adapters and powered off devices
//omitted for sake of brevity
auto bluetoothAdapters = QBluetoothLocalDevice::allDevices();
std::shared_ptr<QBluetoothLocalDevice> localDevice{std::make_shared<QBluetoothLocalDevice>(bluetoothAdapters.at(0).address())};
std::shared_ptr<QBluetoothDeviceDiscoveryAgent> discoveryAgent{std::make_shared<QBluetoothDeviceDiscoveryAgent>(localDevice.get())};
std::shared_ptr<QBluetoothDeviceInfo> targetDeviceInfo{nullptr};
std::shared_ptr<QApplication> findBluetooth{std::make_shared<QApplication>(argc, argv)};
auto setTargetDeviceInfo = [=](QBluetoothDeviceInfo info) {
if (info.name() == TARGET_BLUETOOTH_DEVICE_NAME) {
targetDeviceInfo = std::make_shared<QBluetoothDeviceInfo>(info);
discoveryAgent->stop();
findBluetooth->exit(0);
}
};
auto cancelDiscovery = [=]() {
discoveryAgent->stop();
findBluetooth->exit(1);
};
auto startDiscovery = [=]() {
discoveryAgent->start();
};
QObject::connect(discoveryAgent.get(), &QBluetoothDeviceDiscoveryAgent::deviceDiscovered, setTargetDeviceInfo);
QTimer::singleShot(0, startDiscovery); //startDiscovery get called fine
QTimer::singleShot(BLUETOOTH_DISCOVERY_TIMEOUT, cancelDiscovery); //cancelDiscovery never gets called!
findBluetooth->exec();
//Now check if targetDeviceInfo is nullptr and run the real application etc...
mainApplication->exec();
}发布于 2017-08-24 23:24:20
我最初的帖子有一个重要的遗漏:我遗漏了在main的开头我已经实例化了主QApplication实例。创建两个QApplication实例是导致问题的原因。使用相同的QApplication实例而不是创建两个实例解决了此问题。
发布于 2017-08-24 22:57:07
答:discoveryAgent->start();基本上阻塞了你的主线程。这就是为什么,由QTimer::singleShot(BLUETOOTH_DISCOVERY_TIMEOUT, cancelDiscovery);发布的事件永远不会得到处理-执行discoveryAgent->start()的应用程序没有机会查看事件循环。
https://stackoverflow.com/questions/45864242
复制相似问题