Using the following process the following code fails.
Setup:
First create a container QWidget with HBox layout and two buttons.
When the first button is clicked, switch to VBox layout.
To switch layouts:
- Create a list of child widgets and remove them from the current layout.
- Create a new layout.
- Add the widgets from list to the new layout.
- Set container widget to new layout.
Note: - setParent(None) for children is ineffective.
- setLayout(None) for children is invalid.
- del old layout is ineffective.
Pseudo code test program: s=self, w=widget, wl=widget list
import sys
from PyQt5.QtWidgets import *
class Lw(QWidget):
def __init__(s):
QWidget.__init__(s)
s.lay=QHBoxLayout(); s.setLayout(s.lay)
s.setGeometry(50,45,220,220)
bu0=QPushButton(); bu0.setText("Switch to VBox"); s.lay.addWidget(bu0)
bu0.clicked.connect(s.rslay)
bu1=QPushButton(); bu1.setText("Dummy"); s.lay.addWidget(bu1)
s.show()
def rslay(s):
wl=[]
while s.lay.count()>0:
w=s.lay.takeAt(0).widget()
wl.append(w)
w.setParent(None) # Ineffective
#w.setLayout(None) # Invalid
#del s.lay # Ineffective
s.lay=QVBoxLayout()
s.setLayout(s.lay)
for w in wl: s.lay.addWidget(w)
if __name__== '__main__':
app=QApplication(sys.argv)
lw=Lw()
sys.exit(app.exec()
Program will error:
QWidget::setLayout: Attempting to set QLayout “” on Lw “”, which already has a layout
The child widgets original layout is not dissociated – even if the layout is deleted or its parent is set to None.