Qt5: How to wait for a signal (with filter) in a thread?

73 Views Asked by At

I have read the post how-to-wait-for-a-signal-in-a-thread, but still have some confusions:

What if I want to wait a signal with arguments, and filter the incoming signals based on some specific conditions?
Suppose we have signal: triggered(int i)

QTimer timer;
timer.setSingleShot(true);
QEventLoop loop;
connect( this, &MyClass::triggered, &loop, [&](int i) {
    // only 123 would stop the event loop, otherwise keep waiting until timeout
    if (i == 123)  
        loop.quit();
} );
connect( &timer, &QTimer::timeout, &loop, &QEventLoop::quit );
timer.start(msTimeout);
loop.exec();

if(timer.isActive())
    qDebug("Got 123! It may not be carried by the first incoming signal.");
else
    qDebug("timeout");

Questions:

  • For the first connect, which connected to a lambda, is the third argument &loop necessary?
  • For the first connect, should I disconnect it somewhere?
  • I saw some comments mentioned the inner QEventLoop should be used very careful, why? Am I doing it in the correct manner?
  • Can QSignalSpy class achieve this?
  • Is it possible to rewrite this into a reuseable header template? e.g.waitForTimeout(QObject* sender, Func1 signal, Func2 predicate, int msec)
0

There are 0 best solutions below