Search code examples
pythonqtpyqtpyqt4

Get a layout's widgets in PyQT


I have a QVBoxLayout that I've added a few widgets to, via addWidget(). I need to now delete those widgets, and it seems I need to use removeWidget() (which takes in a widget to be removed) to do that.

I thought that calling children() or findChildren(QWidget) on my layout would return a list of the widgets I've added into it; I'm in the debugger, though, and am just receiving empty lists.

Am I terribly misunderstanding something? I've just started doing PyQT this last week and have mostly been learning through trial and error with the API docs.


Solution

  • That's odd. My understanding is that adding widgets via addWidget transfers ownership to the layout so calling children() ought to work.

    However, as an alternative you could loop over the layout items by using count() and itemAt(int) to supply a QLayoutItem to removeItem(QLayoutItem*).

    Edit:

    I've just tried addWidget with a straight C++ test app. and it doesn't transfer QObject ownership to the layout so children() is indeed an empty list. The docs clearly say that ownership is transferred though...

    Edit 2:

    Okay, it looks as though it transfers ownership to the widget that has that layout (which is not what the docs said). That makes the items in the layout siblings of the layout itself in the QObject hierarchy! It's therefore easier to stick with count and itemAt.

    Edit 3:

    My interpretation of the docs was wrong. I was getting the layout item confused with the widget. The following clarifies what has always been the case.

    https://doc.qt.io/qtforpython-5/overviews/layout.html

    Widgets in a layout are children of the widget on which the layout is installed, not of the layout itself. Widgets can only have other widgets as parent, not layouts.