Qt中使用執行緒時的注意事項(執行緒沒起作用的原因)
阿新 • • 發佈:2019-01-31
今天偶然發現,執行程式時程式輸出視窗中有如下提示:
QObject::startTimer: Timers can only be used with threads started with QThread
也就是當物件有父物件時,是不可以移到其他執行緒當中去的。
程式碼如下:m_Flower為自定義物件,flowerThead為執行緒。
**不起作用的程式碼:
m_Flower=new DispatchFlower(this); flowerThread=new QThread(); m_Flower->moveToThread(flowerThread); connect(this,SIGNAL(sendQuery_GetRTSheetList(QString)),m_Flower,SLOT(getRTDispatchSheetList(QString))); connect(m_Flower,SIGNAL(haveGotDispatchSheetList(QList<DispatchSheet>&)),this,SLOT(editMultiSheets(QList<DispatchSheet>&))); flowerThread->start();
**修改後起作用的程式碼:
m_Flower=new DispatchFlower(); flowerThread=new QThread(); m_Flower->moveToThread(flowerThread); connect(this,SIGNAL(sendQuery_GetRTSheetList(QString)),m_Flower,SLOT(getRTDispatchSheetList(QString))); connect(m_Flower,SIGNAL(haveGotDispatchSheetList(QList<DispatchSheet>&)),this,SLOT(editMultiSheets(QList<DispatchSheet>&))); flowerThread->start();
注意:因m_Flower沒有指定父物件,需要在解構函式中刪除此m_Flowe物件