Remove all items from a layout

The safest way to clear a layout is to extract the items with its takeAt method, and then explicitly delete any widgets with deleteLater:

def clearLayout(self, layout):
    if layout is not None:
        while layout.count():
            item = layout.takeAt(0)
            widget = item.widget()
            if widget is not None:
                widget.deleteLater()
            else:
                self.clearLayout(item.layout())

Leave a Comment