I have a button on my GUI that starts a thread. An additional button that stops the thread by sending a signal to the thread asking it to kill itself by raising an exception. However, even after the thread is dead, the button's signal seems to be connected to any new thread objects including the old ones. So if i've started a 5th thread, the button calls the method 5 times.
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