在Qt程序中使用QEventLoop阻塞执行,如何将10个单独的信号连接到一个循环,使其在收到所有10个信号之前不会解除阻塞?
发布于 2017-12-29 07:48:11
但如果你完全确定你没有办法绕过,你需要有一种方法来存储哪些信号已经触发,哪些没有触发,并且只有在所有信号都触发后才退出事件循环(例如,可能会发出一个连接到事件循环的QEventLoop::quit的信号)。
下面是一个最小的示例,它使用10个具有不同间隔的QTimer,并在退出嵌套事件循环之前等待它们全部触发:
#include <QtCore>
#include <algorithm>
int main(int argc, char* argv[]) {
QCoreApplication a(argc, argv);
const int n = 10;
//10 timers to emit timeout signals on different intervals
QTimer timers[n];
//an array that stores whether each timer has fired or not
bool timerFired[n]= {};
QEventLoop loop;
//setup and connect timer signals
for(int i=0; i<n; i++) {
timers[i].setSingleShot(true);
QObject::connect(&timers[i], &QTimer::timeout, [i, &timerFired, &loop]{
qDebug() << "timer " << i << " fired";
timerFired[i]=true;
//if all timers have fired
if(std::all_of(std::begin(timerFired), std::end(timerFired),
[](bool b){ return b; }))
loop.quit(); //quit event loop
});
timers[i].start(i*i*100);
}
qDebug() << "executing loop";
loop.exec();
qDebug() << "loop finished";
QTimer::singleShot(0, &a, &QCoreApplication::quit);
return a.exec();
}https://stackoverflow.com/questions/48014776
复制相似问题