简体   繁体   中英

Using sleep_for() in Qt application

In my application I want to display some image with this code

myImage = scene->addPixmap(image);
myImage->setOffset(x, y);

Then I want to sleep for some seconds:

std::this_thread::sleep_for(std::chrono::seconds(2));

and then display another image. But this code waits for 2 seconds at first and then displays both images at once. How can I make the program wait between displaying those two images?

Use QTimer::singleShot() and connect it to a slot that updates the picture:

class MyObject : public AQObjectInheritingClass
{
    Q_OBJECT
    ...
public Q_SLOTS:
    void changeImage()
    {
        //change image here
    }

And in instead of sleep_for() :

QTimer::singleShot(2000, &instanceOfMyObject, SLOT("changeImage()");

Two seconds later, changeImage() will be invoked.

You cannot sleep in event based application (GUI applications are event-based). Event based applications have main loop, that has to be running to process events, and update its state. Calling sleep_for stops that main loop, so your app doesn't process events so it doesn't react to input and doesn't repaint itself. That's why all drawing if deferred fot two seconds then flushed at once.

As an alternative, you should use timers, such as QTimer

there is Qt-specific non-blocking way to pause thread with QEventLoop :

QEventLoop loop;
QTimer::singleShot(1000,&loop,SLOT(quit()));
loop.exec();

While loop is being executed, all other events for this thread are processed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM