Search code examples
pythonlayoutpyqtpyqt5qstackedwidget

What's the right way of switching between overlapping layouts? (stacking or replacing layouts)


I'm a PyQT amateur and I have a main layout which is a parent to a left layout and a right layout. With the press of a button, I want to replace the left layout with another one. The "overlapping" left layout should display different things but keep the same proportions. With the press of another button, it should revert back to the original state. The switching should not affect the right side. Dumb drawing here: enter image description here

I don't really understand how QStackedLayout works in this case as it only accepts widgets and not layouts. Can someone give me a tip?

I simply tried removing layout_left from the main layout and adding layout_left_2. This approach might work but the method below only works once and doesn't switch back. This also requires re-setting layout_right because otherwise everything moves chaotically.

# Check if layout_left is active, if yes, then switch to layout_left_2
# and other way around
def switch_layout(self):  
        if self.main_layout.indexOf(self.layout_left) != -1:
            self.main_layout.removeItem(self.layout_left)
            self.main_layout.removeItem(self.layout_right)
            self.main_layout.addItem(self.layout_left_2)
            self.main_layout.addItem(self.layout_right)
        else:
            self.main_layout.removeItem(self.layout_left_2)
            self.main_layout.removeItem(self.layout_right)
            self.main_layout.addItem(self.layout_left)
            self.main_layout.addItem(self.layout_right)

What's the best way to switch layouts?


Solution

  • Sorry I completely forgot to answer my own question. So the comment was right, you can add the layouts to QWidgets, which you then add to a QStackedLayout.

    self.container_left = QtWidgets.QWidget()    
    self.layout_left = QtWidgets.QVBoxLayout(self.container_left)
    ...
    self.container_left_2 = QtWidgets.QWidget()      
    self.layout_left_2 = QtWidgets.QVBoxLayout(self.container_left_2)
    ...
    self.left_stacked_layout = QStackedLayout()
    self.left_stacked_layout.addWidget(self.container_left)
    self.left_stacked_layout.addWidget(self.container_left_2)