[英]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.
但是此代码首先等待2秒钟,然后立即显示两个图像。 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: 使用
QTimer::singleShot()
并将其连接到更新图片的插槽:
class MyObject : public AQObjectInheritingClass
{
Q_OBJECT
...
public Q_SLOTS:
void changeImage()
{
//change image here
}
And in instead of sleep_for()
: 而不是
sleep_for()
:
QTimer::singleShot(2000, &instanceOfMyObject, SLOT("changeImage()");
Two seconds later, changeImage()
will be invoked. 两秒钟后,
changeImage()
将被调用。
You cannot sleep
in event based application (GUI applications are event-based). 您无法在基于事件的应用程序中
sleep
(GUI应用程序是基于事件的)。 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. 调用
sleep_for
停止该主循环,因此您的应用程序不会处理事件,因此不会对输入做出反应,也不会重新绘制自身。 That's why all drawing if deferred fot two seconds then flushed at once. 这就是为什么所有图纸如果推迟两秒钟然后立即刷新。
As an alternative, you should use timers, such as QTimer
作为替代,您应该使用计时器,例如
QTimer
there is Qt-specific non-blocking way to pause thread with QEventLoop
: 有Qt特定的非阻塞方式可以使用
QEventLoop
来暂停线程:
QEventLoop loop;
QTimer::singleShot(1000,&loop,SLOT(quit()));
loop.exec();
While loop is being executed, all other events for this thread are processed. 在执行循环时,将处理此线程的所有其他事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.