[英]pyqt: How to quit a thread properly
我寫了一個pyqt gui並使用線程來運行需要很長時間才能執行的代碼,但是我想選擇安全地停止執行。 我不想使用get_thread.terminate()方法。 我想通過特殊功能(也許是del ())停止代碼。 我的問題是,我在自己的類中編寫了代碼,只是想在不更改大量語法的情況下中止該類。
編輯:有人提到必須將一個標志傳遞給該類,該標志必須不斷檢查。 如何將此標志發送給班級? 因為標志必須更改值,所以當按下停止按鈕時。
編輯2:到目前為止,我的解決方案是派生一個名稱為running_global的全局變量。 我將self.get_thread.terminate()更改為running_global = False,並在long_running_prog中不斷檢查變量是否設置為False。 我認為這種解決方案很難看,所以如果有人有更好的主意,我會很高興。
這是我在其中啟動線程的對話框的代碼:
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嗎? 如果有這種可能,請告訴我如何做?
謝謝您的幫助
希望你能理解我的問題。 問候頭暈
除非prog.run(self)
會定期檢查標志的值以脫離其循環,否則這是不可能的。 一旦實現它,線程上的__del__(self)
應該設置該標志,然后再wait
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.