You can simply reparent the layout to a temporary widget:
def reLayout(self):
QWidget().setLayout(self.layout())
layout = QGridLayout(self)
...
That will reparent all the child widgets to that temporary object, and that object is deleted immediately along with its new children because we don't keep a reference to it.
But the typical way to have multiple layouts for a single widget and to be able to switch between them is to use a QStackedWidget
or QStackedLayout
.
And if you still need the answer to that secondary question:
How to delete the old layout first?
It seems you can't delete directly a QObject
which has a parent, because the parent is keeping a reference to that object. But you can add the object to a temporary QObjectCleanupHandler
which, like the above solution, will be deleted with the object(s) it contains immediately:
QObjectCleanupHandler().add(self.layout())
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…