1
votes

When working with a Qt application, if I create a Widget as the root and have an associated QHboxLayout with the Widget, when I add Widgets into the layout, calling children() on the Widget (root) will return a list of it's children Widgets, including the layout object that is attached to the Widget. When reading the documentation for Qt layouts, layouts are described as something that should be associated with a QWidget, not a child of one, because it can be set calling setLayout. The layout is not rendered, yet the layout has a parent. The layout is responsible for aiding in children resizing for the QWidget.

My question is, why would be a Qlayout have a parent, what purpose is this used for?, and why would a layout be returned as a child of a QWidget with I call children() on the Widget?, I would never want a layout returned, I would expect only Widgets returned, given that it is not actually rendered, unlike a widget, but serves the purpose is aiding in rendering for widget resizing.

1

1 Answers

1
votes

The QWidget and QLayout are QObject, and the QObjects can have a kinship relationship as the docs points out:

QObjects organize themselves in object trees. When you create a QObject with another object as parent, the object will automatically add itself to the parent's children() list. The parent takes ownership of the object; i.e., it will automatically delete its children in its destructor. You can look for an object by name and optionally type using findChild() or findChildren().

And as it is pointed out the main function is to free memory of the children when the parent is destroyed that in C++ it is important to avoid memory leaks, and the same is transferred to Python bindings.

So the layout is the son of the widget so that when the widget is destroyed the layout is also destroyed.

If you want to get the children widget you must use the QObject::findChildren() method:

c++

QList<QWidget *> childrens = widget.findChildren<QWidget *>(Qt::FindDirectChildrenOnly);

python

childrens = widget.findChildren(QtWidgets.QWidget, QtCore.Qt.FindDirectChildrenOnly)

Note: If you want to access the children of the children recursively then you must change Qt::FindDirectChildrenOnly to Qt::FindChildrenRecursively.