Get Layout Widgets in PyQT

I have a QVBoxLayout that I added several widgets through addWidget() . I need to remove these widgets now, and it seems to me that for this I need to use removeWidget() (which accepts the widget that needs to be removed).

I thought that calling children() or findChildren(QWidget) in my layout would return a list of widgets that I added to it; However, I am in the debugger, and I just get empty lists.

Am I terribly misunderstanding something? I just started making PyQT last week and mainly participated in the trial version and errors with the API docs.

+4
source share
2 answers

This is strange. I understand that adding widgets via addWidget transfers ownership of the layout, so calling children() should work.

However, as an alternative, you can itemAt(int) over layout elements using count() and itemAt(int) to deliver a QLayoutItem to removeItem(QLayoutItem*) .

Edit:

I just tried addWidget with a direct C ++ test application. and it does not transfer the QObject property to the layout, so children() really an empty list. docs clearly say that property is being transferred, though ...

Edit 2:

Well, it looks like it is transferring ownership of the widget that has this layout (this is not what the docs said). This makes the elements in the layout of the layout of the layout itself in the QObject hierarchy! Therefore, it is easier to stick with count and itemAt .

+9
source

To get a widget from QLayout, you must call its itemAt(index) method. As the name of this method implies, it returns an element instead of a widget. Calling widget() on the result will finally give you the widget:

 myWidget = self.myLayout.itemAt(index).widget() 

To remove a widget, set the parent widget to None :

 myWidget.setParent(None) 

Also very useful is the QLayout count() method. To find and delete the entire contents of the layout:

 index = myLayout.count() while(index >= 0): myWidget = myLayout.itemAt(index).widget() myWidget.setParent(None) index -=1 
+4
source

Source: https://habr.com/ru/post/1313274/


All Articles