我的GUI上有一个启动线程的按钮。一个额外的按钮,通过向线程发送信号来阻止线程,要求它通过引发异常来自杀。但是,即使在线程死亡之后,按钮的信号似乎也连接到任何新线程对象,包括旧线程对象。因此,如果我已经启动了第5个线程,该按钮会调用该方法5次。
class Worker(QtCore.QObject):
end = QtCore.Signal()
def __init__(self, settings):
super(Worker, self).__init__()
def start_work(self):
self.end_flag = False
try:
print('working')
if(end_flag):
raise KillThread
print('working again')
if(end_flag):
raise KillThread
except KillThread:
print('user clicked stop')
class Gui(QtGui.QMainWindow):
def __init__(self):
super(Gui, self).__init__()
self.ui = Ui_mainWindow()
self.ui.setupUi(self)
# button that starts a new thread
self.ui.start_button.clicked.connect(self.start_work_thread)
def start_work_thread(self):
self.new_thread = QtCore.Qthread()
self.worker = Worker()
self.new_thread.started.connect(self.worker.start_work)
self.new_thread.finished.connect(self.new_thread.quit)
# connects the stop button
self.stop_button.clicked.connect(self.kill_thread)
# moves worker to a thread
self.worker.moveToThread(self.new_thread)
self.new_thread.start()
# invoked when stop button is clicked
def kill_thread(self):
print('killing thread')
self.new_thread.end_flag = True
if __name__ == '__main__':
try:
app = QtGui.QApplication(sys.argv)
main = Gui()
main.show()
sys.exit(app.exec_())
finally:
pass
#save settings