[問題] qt qthread問題

看板C_and_CPP作者 (chec)時間7年前 (2017/05/25 15:51), 7年前編輯推噓2(2010)
留言12則, 4人參與, 最新討論串1/1
開發平台(Platform): (Ex: Win10, Linux, ...) win10 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) vs2015 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) qt5.7 問題(Question): void PC_info::setupTimer(){ timer = new QTimer(0); connect(timer,SIGNAL(timeout(),this,SLOT(OnScan()),Qt::DirectConnection)); timer->start(1000); //thread = new QThread(this); //timer ->moveToThread(thread); //thread->start(); } 大家好 目前在寫定時掃電腦資訊的程式 OnScan是去掃HWinfo關於電腦的資訊 但是進到OnScan的時候 會讓整個ui出現頓感 後來使用QThread來寫的時候 頓感解決 但....會有機率性的讓ui整個凍結 不知道是不是thread的用法錯誤了呢 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 59.124.46.82 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1495698674.A.A84.html

05/25 17:13, , 1F
把 DirectConnection 改 BlockingQueuedConnection 試試
05/25 17:13, 1F

05/25 17:17, , 2F
更新 UI 的時候用 signal/slot
05/25 17:17, 2F

05/25 17:17, , 3F
其實用 QueuedConnection 就好了吧, 沒必要 blocking?
05/25 17:17, 3F

05/25 17:20, , 4F
timeout 應該用 direct 就行,只是更新 UI 要 queue
05/25 17:20, 4F

05/25 17:21, , 5F
其實重點應該是 onscan 要放到 thread 裡, 看上面的程式
05/25 17:21, 5F
是要對thread繼承寫class嗎? 然後每次進去都要new一個thread?

05/25 17:21, , 6F
好像只有 timer 本身在背景執行, 這樣應該沒用
05/25 17:21, 6F

05/25 17:22, , 7F
把 onscan 放到自己的 class 裡, 在 PC_info 初始化後
05/25 17:22, 7F

05/25 17:22, , 8F
moveToThread, 然後 connect 這樣比較合理
05/25 17:22, 8F

05/25 17:24, , 9F
原PO說頓感有解決所以應該已經有在別的執行序
05/25 17:24, 9F

05/25 17:25, , 10F
只是 onscan 裡面直接對 UI 操作可能會當掉
05/25 17:25, 10F
所以thread最好是只做運算 運算結束之後 再emit出來去對ui做操作? ※ 編輯: checkIO (36.226.134.221), 05/25/2017 20:23:08

05/25 20:33, , 11F
以前寫QT時有聽過 UI 最好都在main thread中操作
05/25 20:33, 11F

05/25 20:54, , 12F
開thread掃,掃完emit給main thread讓UI更新
05/25 20:54, 12F
文章代碼(AID): #1P9epog4 (C_and_CPP)