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