Skip to content Skip to sidebar Skip to footer

How To Properly Terminate A Qthread From A Gui Application?

I tried using self.terminate() in the QThread class, and also self.thread.terminate() in the GUI class. I also tried putting self.wait() in both cases. However, there are two scena

Solution 1:

From the Qt documentation for QThread::terminate:

Warning: This function is dangerous and its use is discouraged. The thread can be terminated at any point in its code path. Threads can be terminated while modifying data. There is no chance for the thread to clean up after itself, unlock any held mutexes, etc. In short, use this function only if absolutely necessary.

It's probably a much better idea to re-think your threading strategy such that you can e.g. use QThread::quit() to signal the thread to quit cleanly, rather than trying to get the thread to terminate this way. Actually calling thread.exit() from within the thread should do that depending on how you have implemented run(). If you'd like to share the code for your thread run method that might hint as to why it doesn't work.

Solution 2:

This is what I did:

classMainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    stop_flag = 1
    ...

#=========500 ms class ===================classTimer500msThread(QThread):
    signal_500ms = pyqtSignal(str) 
    ....
    deftimer500msProcess(self):
        if MainWindow.stop_flag == 0 :
            self.timer_500ms.stop()
#==========#=========Main Window ===================
        
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()
MainWindow.stop_flag=0#this sets the flag to 0 and when the next 500ms triggers the #the thread endsprint("Program Ending")

Post a Comment for "How To Properly Terminate A Qthread From A Gui Application?"