How to remove a layout

To delete a layout from its containing layout, you may use


However, the widgets on the child layout remain visible. Layout has no setVisible or hide method for you to show or hide itself. You need to use a QWidget and set its layout to the child layout, then you can control the visibility of the child layout using the setVisible or hide function of QWidget. If you want to switch between two layouts on the same location, you cannot use the setLayout function of QWidget to set the different layout because setLayout won’t let you set the new layout unless you delete the original layout first like this:

delete widget->layout();//delete the first layout


This is inconvenient if you want to switch back to the old layout because it has been deleted. You may think you can backup the old layout before deleting it, however it is not a trivial thing since the = operator of QLayout is private(declared with Q_DISABLE_COPY). What left for you to do is to create a new layout and add the widgets to it one by one to recover the old layout, which is not an easy thing. The simplest way to switch between multiple layouts is: create one QWidget for each layout, add these widgets to the parent layout, and call QWidget ::setVisible (or hide) to set one widget visible and other widgets invisible. Note that when a widget is set invisible, its space is also reclaimed(the location of other widgets is also adjusted). You can also use QStackedWidget to accomplish this task.

Posted in

Comments are closed, but trackbacks and pingbacks are open.