Use another thread to run the timer in QT

Source: Internet
Author: User

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 );}

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.