使用QEventLoop阻止连接到多个信号

问题描述 投票:0回答:1

使用QEventLoop阻止在Qt程序中执行,如何将10个单独的信号连接到一个循环,使得在收到所有10个信号之前它不会被解除阻塞?

qt
1个回答
0
投票

Please avoid using nested loops when possible.但是如果你完全确定你没有办法,你需要有办法存储哪些信号已被触发,哪些信号没有,并退出事件循环(即可能通过发出信号连接到只有当所有信号都被触发时,你的事件循环的QEventLoop::quit)。

下面是一个使用10个不同间隔的QTimers的最小示例,并在退出嵌套事件循环之前等待它们全部触发:

#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();
}
© www.soinside.com 2019 - 2024. All rights reserved.