16
Jul
0

C++ – QSleep, Qt sleep (with a QThread?)

How to make a portable sleep with Qt, or how to sleep when you are programming with Qt…

This technique is a little hack, you may use it carefully.
Because if Qt do not propose a sleep function for a reason! I you make the master thread sleeping your program will freeze (in other work your architecture is not good…) and you may need something else (timer etc.).
Anyway sometime it’s useful to have a portable sleep function.


#include <QtCore/QCoreApplication>
#include <QThread>

class SleepThread : public QThread{
     Q_OBJECT
     // private run
     void run (){}

     public :
     static void usleep(long iSleepTime){
          QThread::usleep(iSleepTime);
     }
     static void sleep(long iSleepTime){
          QThread::sleep(iSleepTime);
     }
     static void msleep(long iSleepTime){
          QThread::msleep(iSleepTime);
     }
};

int main(int argc, char *argv[])
{
     QCoreApplication a(argc, argv);

     qWarning("Start");

     SleepThread::sleep(1);

     qWarning("Stop");

     return a.exec();
}
Enjoyed reading this post?
Subscribe to the RSS feed and have all new posts delivered straight to you.

Comments are closed.

Celadon theme by the Themes Boutique