When compiling a QT program, you often need to use the timer qtimer to execute some scheduled tasks. However, when the scheduled task execution takes too long, the response of the entire interface will be affected, therefore, you may want to use another working thread to execute the timer. Generally, you can choose to derive a Thread class from qthread, and then reload the run and execute the task logic, the following example shows how to use qtimer instead of deriving from qthread.
Add the Class header file in the main window:
QThread* _voiceThread;QTimer* _voiceTimer;
Add constructor:
// Use a thread to run the timer _ voicethread = new qthread; _ voicetimer = new qtimer; _ voicetimer-> setsingleshot (true); // start the timer before movetothread, otherwise, calling start will fail _ voicetimer-> Start (200); _ voicetimer-> movetothread (_ voicethread ); // The timer object and this are not in the same thread, so the connection mode is QT: directconnection, which is directly triggered by the thread where the timer is located _ onvoicetimeoutconnect (_ voicetimer, signal (timeout (), this, slot (_ onvoicetimeout (), QT: directconnection); // connects the timer slot to stop the timer connect (this, signal (stop (), _ voicetimer, slot (stop (); _ voicethread-> Start ();
Add destructor:
emit stop();_voiceThread->quit();_voiceThread->wait();delete _voiceTimer;delete _voiceThread;
Timer slot:
Void test: _ onvoicetimeout () {// execute the task //... _ voicetimer-> Start (1000 );}