Qt delay processing of several ways

Sometimes, we need to delay the program for a while:

Here are four ways to provide:

1, a multi-threaded program using QThread :: sleep () or QThread :: msleep () or QThread :: usleep () or QThread :: wait () any delay.

Sleep does not release the object lock, other threads can not access the object, thus blocking the thread; and Wait releases the object lock, so that other threads can access the object.

 

2, since the delay function is defined:
use QEventLoop

1 void Widget::Sleep(int msec)
2 {
3     QTime dieTime = QTime::currentTime().addMSecs(msec);
4     while( QTime::currentTime() < dieTime )
5         QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
6 }

Incoming parameters msec, the program delay msec milliseconds. This method does not block the current thread, especially for Qt UI with a single-threaded program, or UI thread, because when the thread is blocked,

The phenomenon is very obvious UI stuck. Of course, you can also change the program delay addMSecs to addSecs msec seconds.

If you remove QCoreApplication :: processEvents (QEventLoop :: AllEvents, 100); it can be delayed, but it can also block the thread

QCoreApplication::processEvents(QEventLoop::AllEvents, 100);

Wait while the program period, to deal with what this thread event loop, loop handle events up to 100ms This statement must be returned, if the process is completed in advance, then immediately return to this statement.


3, using QElapsedTimer
header file:#include <QElapsedTimer>

1 QElapsedTimer t;
2 t.start();
3 while(t.elapsed()<10000);

The code that the program delay 10S (10000MS), but this method will block the thread.

 

4, create a sub-cycle event, cycle event in the child, the parent event loop can still be executed
this method does not block the thread

. 1  void Delay_MSec (unsigned int msec)
 2  {
 . 3      QEventLoop Loop; // define a new event loop 
. 4      QTimer :: SingleShot (msec, & Loop, the SLOT (quit ())); // Create a single timer, the slot function event loop exit function 
. 5      loop.exec (); // event loop begins execution, the program will be stuck here until the regular time, the loop is exited 
6  }

Guess you like

Origin www.cnblogs.com/ybqjymy/p/12169842.html