0

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.

  • First of all, I strongly advise you against using the string representation of a widget (or an object for what matters) as an objectName. That said, *what* does not work in your case? Do you get an error? – musicamante Nov 26 '19 at 10:22
  • The error I get is: gui object has no attribute widgets. – Luggie Böörgöör Nov 26 '19 at 10:37
  • I found this that somehow saves some code lines : some_widget = QSomeWidget(..., objectName='button1', ...) but doesn't fully answer my own question. – Luggie Böörgöör Nov 26 '19 at 10:48
  • That doesn't seem to have nothing to do with object names. What is "gui"? – musicamante Nov 26 '19 at 10:53
  • 1
    It would also help a lot if you provide us a [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – musicamante Nov 26 '19 at 11:04
  • @musicamante: I meant self.widgets(). – Luggie Böörgöör Nov 26 '19 at 11:35
  • 1
    As far as I know, the `widgets()` function does not exist in any QObject or QWidget class. Is it possible that you implemented in your old code and forgot to update it? Or maybe you used search/replace for something else, resulting in renaming that function? – musicamante Nov 26 '19 at 11:59
  • You could try `self.children()` which would return all child objects. – Heike Nov 26 '19 at 12:19

1 Answers1

1

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.

musicamante
  • 41,230
  • 6
  • 33
  • 58