本文介绍了PyQt - 小部件的父级 - 有必要吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用一些小部件创建 GUI,所有这些小部件都没有指定父级.效果很好.

I tried creating GUI with a few widgets, all of them without secifying a parent.It worked fine.

这样可以吗,还是有理由指定父级?

Is this Ok, or there is reason to specify the parent?

谢谢!

推荐答案

一般来说,最好尽可能指定父级,因为这有助于避免对象清理问题.这在退出程序时最常见,因为 Python 垃圾收集器固有的随机性可能意味着对象有时会以错误的顺序被删除,从而导致程序崩溃.

In general, it's better to specify a parent wherever possible, because it can help avoid problems with object cleanup. This is most commonly seen when exiting the program, when the inherent randomness of the python garbage-collector can mean objects sometimes get deleted in the wrong order, causing the program to crash.

然而,这个问题的发现通常不会影响标准的 GUI 小部件,因为一旦它们被添加到布局中,Qt 会自动重新设置它们的父级.问题较多的对象是与视图密切相关的项目模型、项目委托、图形场景等.

However, this find of problem does not usually affect the standard GUI widgets, because Qt will automatically reparent them once they have been added to a layout. The more problematic objects are things like item-models, item-delegates, graphics-scenes, etc, which are closely linked to a view.

理想情况下,pyqt 程序应该有一个根窗口,所有其他对象都在父子层次结构中连接到它.当根被删除/关闭时,Qt 也会递归地删除它的所有子对象.这应该只留下 pyqt 包装器对象,可以安全地留给 python 垃圾收集器清理.

Ideally, a pyqt program should have one root window, with all the other objects connected to it in a parent-child hierarchy. When the root is deleted/closed, Qt will recursively delete all its child objects as well. This should leave only the pyqt wrapper objects behind, which can be safely left to the python garbage-collector to clean up.

指定父级的一个更具建设性的好处是,它只是让对象更容易相互访问.例如,一个常见的习惯用法是通过它们的父级迭代一组按钮:

A more constructive benefit of specifying parents, is that it simply makes objects more accessible to one another. For instance, a common idiom is to iterate over a group of buttons via their parent:

    for button in parent.findChildren(QAbstractButton):
        print(button.text())

这篇关于PyQt - 小部件的父级 - 有必要吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 19:44