2016-09-20 1562 views
1

我試圖在完成處理後退出線程。我正在使用moveToThread。我試圖通過在槽中調用self.thread.quit()從主線程退出工作線程。這不起作用。如何在使用moveToThread時正確退出PyQt5中的QThread

我發現了幾個使用moveToThread啓動線程的例子,比如這個。但我找不到如何退出。

from PyQt5.QtCore import QObject, QThread 
from PyQt5.QtCore import pyqtSlot, pyqtSignal 
from PyQt5.QtWidgets import QMainWindow 

class MainWindow(QMainWindow): 
    def __init__(self): 
     super().__init__() 
     print("Base init") 
     self.start_thread() 

    @pyqtSlot(int) 
    def onFinished(self, i): 
     print("Base caught finished, {}".format(i)) 
     self.thread.quit() 
     print('Tried to quit thread, is the thread still running?') 
     print(self.thread.isRunning()) 

    def start_thread(self): 
     self.thread = QThread() 
     self.w = Worker() 
     self.w.finished1[int].connect(self.onFinished) 
     self.w.moveToThread(self.thread) 
     self.thread.started.connect(self.w.work) 
     self.thread.start() 

class Worker(QObject): 
    finished1 = pyqtSignal(int) 

    def __init__(self): 
     super().__init__() 
     print("Worker init") 

    def work(self): 
     print("Worker work") 
     self.finished1.emit(42) 


if __name__ == "__main__": 
    import sys 
    from PyQt5.QtWidgets import QApplication 

    app = QApplication(sys.argv) 
    mw = MainWindow() 
    mw.show() 

sys.exit(app.exec_()) 

這是我所有的打印功能輸出(當然沒有的顏色):

Base init 
Worker init 
Worker work 
Base caught finished, 42 
Tried to quit thread, is the thread still running? 
True 

回答

0

嘗試運行腳本多次。致電self.thread.isRunning()的結果總是一樣嗎?在檢查線程是否仍在運行之前,嘗試添加對time.sleep(1)的調用。注意有什麼不同?

請記住,您正在從程序的主線程調用另一個線程,該線程根據定義是異步的。在執行下一條指令之前,您的程序不會等待以確保self.thread.quit()已完成。

+0

謝謝!你是對的。畢竟,線程正在退出。 print(self.thread.isRunning())顯示False添加time.sleep(1)後, – squirtgun