Attendre la fin d’un signal Qt de manière synchrone

Publié dans Snippet | Marqué avec , , ,
Share

Ou comment attendre la fin d’une méthode asynchrone.

Snippet

/**
 * Wait synchronously for a Qt signal (+ timeout management)
 * May be useful for test purpose
 * Not recommended for production usage
 */

// -- Configure the waiting
// Signal to wait
QEventLoop loop;
QObject::connect(&anObject, SIGNAL(signalToWait()), &loop, SLOT(quit()));
// Timeout to avoid infite waiting
QTimer timer;
timer.setInterval(10*1000); //10s
timer.setSingleShot(true);
QObject::connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));

// -- Do stuff that should trigger the signal
// ...

// -- Start to wait
// What is done after "loop.exec()" is not executed until "loop.quit()" is called
timer.start();
loop.exec();
timer.stop(); // Just in case there is no timeout

// -- Other stuff
// ...

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*