gpt4 book ai didi

c++ - QTimer::singleShot 仅在间隔为 0 时调用 lambda

转载 作者:行者123 更新时间:2023-11-28 05:01:21 33 4
gpt4 key购买 nike

注意:我的原始帖子有一个重要的遗漏:我遗漏了我已经在 main 的开头实例化了主 QApplication 实例。创建两个 QApplication 实例是导致问题的原因。使用相同的 QApplication 实例而不是创建两个实例解决了这个问题。

我的意图是在主应用程序之前运行一个 QApplication 来迭代可用的蓝牙设备,以找到一个特定的设备。如果在特定的时间限制内没有找到特定的,则终止 QApplication。第一个存储的 lambda (startDiscovery) 在 QApplication::exec() 被调用时被调用,但是第二个存储的 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();

}

最佳答案

回答:discoveryAgent->start(); 基本上阻塞了你的主线程。这就是为什么 QTimer::singleShot(BLUETOOTH_DISCOVERY_TIMEOUT, cancelDiscovery); 发布的事件永远不会被处理 - 应用程序执行 discoveryAgent->start() 并且没有机会查看事件循环。

关于c++ - QTimer::singleShot 仅在间隔为 0 时调用 lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45864242/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com