Correct way to close QMainWindow

可紊 提交于 2021-01-29 08:39:17

问题


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?


回答1:


close():

Closes this widget.

destroy():

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.



来源:https://stackoverflow.com/questions/62909755/correct-way-to-close-qmainwindow

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!