2016-10-04 3415 views
0

我寫了一個pyqt gui,並使用線程來運行需要很長時間才能執行的代碼,但我想要選擇安全地停止執行。我不想使用get_thread.terminate()方法。我想通過特殊功能停止代碼(也許del())。我的問題是,我在自己的類中編寫代碼,只想在不改變大量語法的情況下中止該類。pyqt:如何正確退出線程

編輯:有人提到,必須通過一個標誌的班級,這必須不斷檢查。我如何將這個標誌發送給班級?由於標誌必須改變該值,所以當按下停止按鈕時。

編輯2:到目前爲止,我的解決方案是使用名稱running_global刪除全局變量。我將self.get_thread.terminate()更改爲running_global = False,並且如果該變量已設置爲False,我會不斷檢查long_running_prog。我認爲這個解決方案很難看,所以如果有人有更好的想法,我會很開心。

這是我的對話框代碼,我啓動線程:

class SomeDialog(QtGui.QDialog, 
    userinterface_status.Ui_status_window): 
    finished = QtCore.pyqtSignal(bool) 

    def __init__(self): 
     """ 
     :param raster: Coordinates which are going to be scanned. 
     """ 
     super(self.__class__, self).__init__() # old version, used in python 2. 
     self.setupUi(self) # It sets up layout and widgets that are defined 
     self.get_thread = SomeThread() 

     # Conencting the buttons 
     self.start_button.clicked.connect(self.start) 
     self.stop_button.clicked.connect(self.stop) 
     self.close_button.clicked.connect(self.return_main) 

     # Connecting other signals 
     self.connect(self.get_thread, QtCore.SIGNAL("stop()"), self.stop) 
     self.connect(self.get_thread, QtCore.SIGNAL("update_status_bar()"), self.update_status_bar) 

    def return_main(self): 
     """ 
     Function is excecuted, when close button is clicked. 
     """ 
     print("return main") 
     self.get_thread.terminate() 
     self.close() 

    def start(self): 
     """ 
     Starts the thread, which means that the run method of the thread is started. 
     """ 
     self.start_button.setEnabled(False) 
     self.get_thread.start() 

    def stop(self): 
     print("Stop programm.") 
     self.start_button.setEnabled(True) 
     self.get_thread.quit() 

    def end(self): 
     QtGui.QMessageBox.information(self, "Done!", "Programm finished") 



    def closeEvent(self, event): 
     """ 
     This method is called, when the window is closed and will send a signal to the main window to activaete the 
     window again. 
     :param event: 
     """ 
     self.finished.emit(True) 
     # close window 
     event.accept() 

在下面的類是線程的代碼:

class SomeThread(QtCore.QThread): 
    finished = QtCore.pyqtSignal(bool) 

    def __init__(self): 
     QtCore.QThread.__init__(self) 

    def __del__(self): 
     print("del") 
     self.wait() 

    def run(self): 
     self.prog = long_running_prog(self.emit) # Sending from the prog signals 
     self.prog.run() 
     self.prog.closeSystem() # Leaving the programm in a safe way. 

所以,如果一個印刷機停止按鈕,程序應立即以保存方式關閉。有沒有辦法以保存的方式中止課程?例如,當我按下停止按鈕時,是否可以將變量傳遞給long_running_prog類,該類變爲True?如果這樣的事情是可能的,能告訴我怎麼做?

感謝您的幫助提前

我希望你能理解我的問題。 Greetings Hizzy

+0

[如何從GUI應用程序中正確終止QThread?](http://stackoverflow.com/questions/7928044/how-to-properly-terminate-a-qthread-from-a-gui-應用程序) –

+0

我讀了這個問題和答案,但它沒有幫助我。 – Hizzy

回答

0

這是不可能的,除非prog.run(self)會定期檢查一個標誌的值來擺脫它的循環。一旦你實現它,線程上的__del__(self)應該設置標誌,然後wait

+0

好的,我想這是快速實施。你能給我寫一些示例代碼嗎?謝謝你的幫助。 – Hizzy