How to give a delay in loop execution using Qt

In my application I want that when a loop is being executed, each time the control transfers to the loop, each execution must be delayed by a particular time. How can I do this?

Answers


EDIT (removed wrong solution). EDIT (to add this other option):

Another way to use it would be subclass QThread since it has protected *sleep methods.

QThread::usleep(unsigned long microseconds);
QThread::msleep(unsigned long milliseconds);
QThread::sleep(unsigned long second);

Here's the code to create your own *sleep method.

#include <QThread>    

class Sleeper : public QThread
{
public:
    static void usleep(unsigned long usecs){QThread::usleep(usecs);}
    static void msleep(unsigned long msecs){QThread::msleep(msecs);}
    static void sleep(unsigned long secs){QThread::sleep(secs);}
};

and you call it by doing this:

Sleeper::usleep(10);
Sleeper::msleep(10);
Sleeper::sleep(10);

This would give you a delay of 10 microseconds, 10 milliseconds or 10 seconds, accordingly. If the underlying operating system timers support the resolution.


As an update of @Live's answer, for Qt ≥ 5.2 there is no more need to subclass QThread, as now the sleep functions are public:

Static Public Members
  • QThread * currentThread()
  • Qt::HANDLE currentThreadId()
  • int idealThreadCount()
  • void msleep(unsigned long msecs)
  • void sleep(unsigned long secs)
  • void usleep(unsigned long usecs)
  • void yieldCurrentThread()

cf http://qt-project.org/doc/qt-5/qthread.html#static-public-members


C++11 has some portable timer stuff. Check out sleep_for.


Need Your Help

How to pass more than one parameter to a C# thread?

c# multithreading

How to pass more than one parameter to a C# thread? Any example will be appreciated.