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&loopnecessary? - For the first
connect, should Idisconnectit somewhere? - I saw some comments mentioned the inner
QEventLoopshould be used very careful, why? Am I doing it in the correct manner? - Can
QSignalSpyclass achieve this? - Is it possible to rewrite this into a reuseable header template? e.g.
waitForTimeout(QObject* sender, Func1 signal, Func2 predicate, int msec)