PyQt5: How to assign ObjectName to all Objects with setObjectName

758 Views Asked by At

How can I assign ObjectNames for all QWidgets, QLayouts, QFrames etc in my gui class? Code like this only work in PyQt4:

for w in gui.widgets():
   w.setObjectName(str(w)

How does this work in PyQt5? Also how can I iterate over all objects and not "just" widgets? I know that there are some answers for that question for C++ however I can't translate them into python.

1

There are 1 best solutions below

0
musicamante On

There is no widget() function for main QObject or QWidget classes, so you probably implemented in your own code and forgot to update it when updating for PyQt5.

To access all children objects, just use findChildren with QObject as first argument, which will return all descendants of QObject classes, including QWidgets, QActions, item models, etc:

for child in self.findChildren(QObject):
    pass

Since findChildren finds recursively by default, you can also limit to direct children of the current object:

for child in self.findChildren(QObject, options=FindDirectChildrenOnly):
    pass

In this case, the result will be the same as self.children().

Note that not all classes in Qt inherit from QObject.