Quickly resolve the problem of different exit times for sub threads after pyqt5 form shutdown

  • 2021-06-28 13:36:17
  • OfStack

A main form has been designed with pyqt5, which requires an infinite loop to work on a thread while the form is running.After running, it is found that after closing the main form by pressing the close key of the main form with the mouse, the thread does not automatically terminate and is still running.Although this is not a problem for my usage scenario, it shuts down immediately.During debugging, however, you hate it because background threads are very resource intensive.How can I get the main form to close and the child threads to exit as well?Baidu for a long time, many methods are not possible.

The main things you've tried are:

1. Settings: self.thread.Daemon=True

2. Set a variable in the sub-thread to end the loop automatically by changing the value of the variable so that the loop does not meet the criteria

3. Setting up a destructor

There are other wonderful flowers.None of them.

Today, it's actually very simple.Is the closeEvent() function that reconstructs the main form.


def closeEvent(self,event):

   sys.exit(app.exec_())

Originally, there was this code in the main program. It is estimated that the main form was pushed by X without starting this code, so the sub-thread will not end.Refactoring this function solves the problem.


Related articles: