1. 程式人生 > 其它 >Qt UI執行緒避免執行耗時任務

Qt UI執行緒避免執行耗時任務

技術標籤:Qt

Qt中的UI執行緒避免執行耗時任務,具體說明如下。

  • UI不要執行耗時方法,會造成介面卡死現象。
  • Qt中訊號對應的槽函式也不要執行耗時任務,同樣會造成阻塞。

測試程式如下

//自定義QObject子類
//.h檔案
class MyObject : public QObject
{
public:
    explicit MyObject(QObject *parent = nullptr);

public slots:
    void testCost(){
        while (true) {
            qDebug()<<"do cost "<<QDateTime::currentDateTime().toString("hh:mm:ss");
            emit doCost();
            QThread::sleep(1);
        }
    }

    void doCostTask(){
        QThread::sleep(3);
        qDebug()<<"==do cost enddddddddd "            <<QDateTime::currentDateTime().toString("hh:mm:ss");
    }

signals:
    void doCost();

}

//.cpp檔案
MyObject::DataObject(QObject *parent) : QObject(parent)
{
    connect(this, &MyObject::doCost, this, &MyObject::doCostTask);
}

測試結果如下: