PyQt – parent for widgets – necessary?

Question:

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?

Thanks!

Asked By: Israel Unterman

||

Answers:

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.

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.

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())
Answered By: ekhumoro