what can I use to replace sleep and usleep in my Qt app?


Question

I'm importing a portion of existing code into my Qt app and noticed a sleep function in there. I see that this type of function has no place in event programming. What should I do instead?

UPDATE: After thought and feedback I would say the answer is: call sleep outside the GUI main thread only and if you need to wait in the GUI thread use processEvents() or an event loop, this will prevent the GUI from freezing.

1
10
7/25/2011 6:02:14 PM

Accepted Answer

It is not necessary to break down the events at all. All I needed to do was to call QApplication::processEvents() where sleep() was and this prevents the GUI from freezing.

3
10/3/2017 1:23:05 PM

It isn't pretty but I found this in the Qt mailing list archives:

The sleep method of QThread is protected, but you can expose it like so:

class SleeperThread : public QThread
{
public:
    static void msleep(unsigned long msecs)
    {
        QThread::msleep(msecs);
    }
};

Then just call:

SleeperThread::msleep(1000);

from any thread.

However, a more elegant solution would be to refactor your code to use a QTimer - this might require you saving the state so you know what to do when the timer goes off.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon