QT Start timer with thread

Source: Internet
Author: User

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

    1. qthread* _voicethread;

    2. qtimer* _voicetimer;


Constructor join:



[CPP] view plain copy

  1. //Use a thread to run the timer   

  2. _voicethread = new qthread;

  3. _voicetimer = new Qtimer;

  4. _voicetimer->setsingleshot (true);

  5. //Start the timer before Movetothread, or not in a thread, call start directly will fail   

  6. _voicetimer->start (200);

  7. _voicetimer->movetothread (_voicethread);

  8. //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   

  9. Connect (_voicetimer, SIGNAL (), this , SLOT (_onvoicetimeout ()), Qt::D irectconnection);

  10. //Connect the timer slot to stop the timer   

  11. Connect (this, SIGNAL (Stop ()), _voicetimer, SLOT (Stop ()));

  12. _voicethread->start ();


Destructor joins:



[CPP] view plain copy

  1. Emit stop ();

  2. _voicethread->quit ();

  3. _voicethread->wait ();

  4. Delete  _voicetimer;

  5. Delete  _voicethread;


Timer Slots:



[CPP] view plain copy

  1. void test::_onvoicetimeout ()

  2. {

  3. //Perform Tasks   

  4. // ...   

  5. _voicetimer->start (1000);

  6. }


QT Start timer with thread

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.