[Qt-interest] Delay of code execution

Denis Akhmetzyanov dakhmetzyanov at smartlabs.tv
Wed Apr 14 12:58:46 CEST 2010


Hi,
I've used QTest::qWait() method for delay. It's advantage that events will
be processed while waiting. GUI and network won't frozen. It has a trivial
short implementation and can be moved to application if dependency on
QTestLib is unwanted.

    // non-blocking wait
    inline static void qWait(int ms)
    {
        Q_ASSERT(QCoreApplication::instance());

        QTime timer;
        timer.start();
        do {
            QCoreApplication::processEvents(QEventLoop::AllEvents, ms);
            QTest::qSleep(10);
        } while (timer.elapsed() < ms);
    }

// blocking wait
void QTest::qSleep(int ms)
{
    QTEST_ASSERT(ms > 0);

#ifdef Q_OS_WIN
    Sleep(uint(ms));
#else
    struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 };
    nanosleep(&ts, NULL);
#endif
}


2010/4/13 Matthias Pospiech <matthias.pospiech at gmx.de>

> 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.
>
> Matthias
> _______________________________________________
> Qt-interest mailing list
> Qt-interest at trolltech.com
> http://lists.trolltech.com/mailman/listinfo/qt-interest
>



-- 
Best regards,
Denis Akhmetzyanov
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20100414/f22a9a50/attachment.html 


More information about the Qt-interest-old mailing list