When writing a QT program, it is often necessary to use the timer Qtimer to perform some timed tasks, but when the timed task executes too long, it will affect the response of the entire interface, so it is expected to use another worker thread to execute the timer, in general you can choose to derive a thread class from Qthread. Then overload run and execute the task logic, and here's an example that doesn't derive from Qthread and use Qtimer.
Main window class header file join:
[CPP] view plain copy
qthread* _voicethread;
qtimer* _voicetimer;
Constructor join:
[CPP] view plain copy
//Use a thread to run the timer
_voicethread = new qthread;
_voicetimer = new Qtimer;
_voicetimer->setsingleshot (true);
//Start the timer before Movetothread, or not in a thread, call start directly will fail
_voicetimer->start (200);
_voicetimer->movetothread (_voicethread);
//Timer object and this is not in a thread, so the connection is specified here as QT::D irectconnection, triggered directly by the timer thread _onvoicetimeout
Connect (_voicetimer, SIGNAL (), this , SLOT (_onvoicetimeout ()), Qt::D irectconnection);
//Connect the timer slot to stop the timer
Connect (this, SIGNAL (Stop ()), _voicetimer, SLOT (Stop ()));
_voicethread->start ();
Destructor joins:
[CPP] view plain copy
Emit stop ();
_voicethread->quit ();
_voicethread->wait ();
Delete _voicetimer;
Delete _voicethread;
Timer Slots:
[CPP] view plain copy
void test::_onvoicetimeout ()
{
//Perform Tasks
// ...
_voicetimer->start (1000);
}
QT Start timer with thread