Reputation: 537
I recently changed from tkinter to Pyqt5 as I'm developing a semi-large application in Python 3.7.8
Every time I had to close windows I used the method self.destroy()
, and there was a small chance that, when I closed all the program and having no windows, the interpreter was still running and I needed to terminate the process manually, even when using sys.exit(app.exec_())
I could had the program running for 15 seconds or 30 minutes, it was completely random.
I just saw another method that is called self.close()
, so I replaced the self.destroy()
with it, but I'm not sure if this is the intended practice or if there is a better way. I still have to check if the problem doesn't appear again.
It's better to use self.destroy
or self.close
for pyqt5 applications?
Is there a better way?
Upvotes: 6
Views: 10191
Reputation: 48489
Closes this widget.
Frees up window system resources. [...] This function is usually called from the QWidget destructor.
If you close()
the widget, it can be opened/shown again later if required, but if the widget is a top level window and is the last visible one, Qt will automatically quit the application (assuming the QApplication has the quitOnLastWindowClosed()
set, which is the default behavior). In this case PyQt will automatically destroy the window and free up memory, meaning that destroy()
will be called anyway.
Note that the window will also be automatically destroyed when closed if it has no other reference or parent: as much as any other python object, the garbage collector will delete the widget and its children, which causes a call to the QWidget destroyer.
So, you should always call close()
, since it ensures that Qt follows the correct steps: send a QCloseEvent (which could be ignored, if required) and notify the application about that, so that it can actually quit if the window was the last one.
Upvotes: 7