关闭 QMainWindow 的正确方法 [英] Correct way to close QMainWindow

查看:874
本文介绍了关闭 QMainWindow 的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近从 tkinter 更改为 Pyqt5,因为我正在使用 Python 3.7.8 开发一个半大型应用程序

I recently changed from tkinter to Pyqt5 as I'm developing a semi-large application in Python 3.7.8

每次我不得不关闭窗口时,我都使用方法 self.destroy(),当我关闭所有程序并且没有窗口时,解释器仍然存在的可能性很小运行,我需要手动终止进程,即使使用 sys.exit(app.exec_())

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_())

我可以让程序运行 15 秒或 30 分钟,这完全是随机的.

I could had the program running for 15 seconds or 30 minutes, it was completely random.

我刚刚看到了另一个名为 self.close() 的方法,所以我用它替换了 self.destroy(),但我不确定是否这是预期的做法,或者如果有更好的方法.我还要检查问题是否再次出现.

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.

pyqt5 应用程序使用 self.destroy 还是 self.close 更好?有没有更好的办法?

It's better to use self.destroy or self.close for pyqt5 applications? Is there a better way?

推荐答案

<代码>关闭():

关闭这个小部件.

destroy():

释放窗口系统资源.[...]该函数通常从 QWidget 析构函数中调用.

Frees up window system resources. [...] This function is usually called from the QWidget destructor.

如果您close()小部件,它可以在需要时稍后再次打开/显示,但是如果小部件是顶级窗口 是最后一个可见的,Qt 会自动退出应用程序(假设 QApplication 有 quitOnLastWindowClosed() 设置,这是默认行为).在这种情况下,PyQt 将自动销毁窗口并释放内存,这意味着无论如何都会调用 destroy().

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.

请注意,如果窗口没有其他引用或父对象,则窗口在关闭时也会自动销毁:与任何其他 python 对象一样,垃圾收集器将删除小部件及其子部件,这导致调用 QWidget 销毁器.

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.

因此,您应该始终调用 close(),因为它确保 Qt 遵循正确的步骤:发送 QCloseEvent(如果需要,可以忽略)并通知应用程序,因此如果窗口是最后一个,它实际上可以退出.

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.

这篇关于关闭 QMainWindow 的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆