Wednesday, April 7, 2010

[Solution] How to make a Qt thread sleep?

First, consider using sleep(), msleep() or usleep() static methods of QThread class.

However, they are marked as protected, so you can call them only in a QThread subclass.

If for some reason you can't use QThread methods, the following small utility class will help you:

#include <QWaitCondition>
#include <QMutex>

class Sleep
    // Causes the current thread to sleep for msecs milliseconds.
    static void msleep(unsigned long msecs)
        QMutex mutex;
        QWaitCondition waitCondition;
        waitCondition.wait(&mutex, msecs);