Qt 定时器signal/slot阻塞主线程界面

来源:互联网 发布:中西部地区的淘宝村 编辑:程序博客网 时间:2024/05/17 05:06
Qt 定时器signal/slot阻塞主线程界面
示例代码:
<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>


这里定时器每秒执行一次uploadDeviceStatusSlot(),它都是在主界面线程中运行的,如果它很耗时就会导致主界面出现僵死的现象。
signal与SLOT默认是以 Qt::AutoConnection 方式连接的,如果signal与SLOT接收者在不同的线程中,就会以Qt::QueuedConnection方式连接(SLOT在接收的线程运行),否则以Qt::DirectConnection方式连接(SLOT是直接运行的).
所以就算是定时器,它产生的调用也有可能是在主线程中运行,就会挂起主界面,解决方法是把SLOT放到另一线程中的对象上。
<span style="font-size:18px;">class Sloter : public QObject{    Q_OBJECTpublic slots:    void uploadDeviceStatusSlot() { bicycle->uploadDeviceStatusSlot(); } // 这里调用bicycle中的函数};bicycle::bicycle(QWidget *parent) :    QMainWindow(parent){    QThread *thread = new QThread();    Sloter *sloter = new Sloter();    QTimer *timer = new QTimer(this);    sloter->moveToThread(thread); // 这里是关键    connect(timer, SIGNAL(timeout()), sloter, SLOT(uploadDeviceStatusSlot())); // 连接时,signal与Sloter的对象连接    timer->start(1000);}</span>
作者:帅得不敢出门 程序员群:31843264

0 0
原创粉丝点击