Qt timer signal/slot blocks the main thread interface, signalslot

Source: Internet
Author: User

Qt timer signal/slot blocks the main thread interface, signalslot
Qt timer signal/slot blocking main thread Interface
Sample Code:

<span style="font-size:18px;">class bicycle : public QMainWindow{public slots:    void uploadDeviceStatus();};bicycle::bicycle(QWidget *parent) :    QMainWindow(parent){    QTimer *timer = new QTimer(this);    connect(timer, SIGNAL(timeout()), this, SLOT(uploadDeviceStatusSlot()));    timer->start(1000);}</span>


Here, the timer executes uploadDeviceStatusSlot () every second. It runs in the main interface thread. If it takes a long time, it will cause the main interface to become stiff.
By default, signal and SLOT are connected in the Qt: AutoConnection mode. IF signal and SLOT are in different threads :: queuedConnection (SLOT is run in the receiving thread); otherwise, it is connected using Qt: DirectConnection (SLOT runs directly ).
So even if it is a timer, the call may be executed in the main thread, and the main interface will be suspended. The solution is to put the SLOT on the object in another thread.
<Span style = "font-size: 18px;"> class Sloter: public QObject {Q_OBJECTpublic slots: void uploadDeviceStatusSlot () {bicycle-> uploadDeviceStatusSlot ();} // call the function} in bicycle here; bicycle: bicycle (QWidget * parent): QMainWindow (parent) {QThread * thread = new QThread (); sloter * sloter = new Sloter (); QTimer * timer = new QTimer (this); sloter-> moveToThread (thread); // here is the key connect (timer, SIGNAL (timeout (), sloter, SLOT (uploadDeviceStatusSlot (); // when connected, signal connects to the Sloter object timer-> start (1000 );} </span>
Author: handsome, dare not go out, programmer group: 31843264

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.