[Qt-interest] Delay of code execution

Sean Harmer sean.harmer at maps-technology.com
Tue Apr 13 19:00:47 CEST 2010


On Tuesday 13 Apr 2010 16:09:49 Matthias Pospiech wrote:
> I was using the following code:
> 
> --- delay.h ----
> #include <QtCore/QTime>
> inline void delay(long ms)
> {
>         QTime time;
>         time.start();
>         while (time.elapsed()<ms);
> }
> 
> then I found that the following should be possible as well:
> 
> --- delay.h ----
> #include <QtCore/QThread>
> 
> class SleeperThread : public QThread
> {
> public:
>     static void msleep(unsigned long msecs)
>     {
>         QThread::msleep(msecs);
>     }
> };
> 
> inline void delay(long ms)
> {
>        SleeperThread::msleep(ms);
> }
> 
> 
> If I however use the latter approach inside a thread I see that the
> function delay(1000) returns immediately.
> Did I understand something wrong? Which is the recommanded solution?
> I know that in a thread I could as well use msleep, but I would like to
> have a solution which can be used anywhere
> in the programm and also outside of QThread classes.

Why put the thread into a non-responsive state by sleeping or spinning in a 
loop? You can simply use a single shot timer to call a slot at after a 
specified delay whilst allowing the event loop to process events in the 
interim:

void MyClass::delayExecution( int ms )
{
    QTimer::singleShot( ms, this, carryOn() );
}

void MyClass::carryOn()
{
    // do something useful
}

Sean



More information about the Qt-interest-old mailing list