Search code examples
pythonpyqtqstackedwidget

Including QStackedLayout messes up layout


My main layout is an HBoxLayout with a Textedit on the left and some PushButtons in a VBoxlayout on the right. And there is some nesting for the buttons on the top_right.

    but1 = QPushButton('button 1')
    but2 = QPushButton('button 2')
    but3 = QPushButton('button 3')

    right_top_widget = QWidget()
    right_top_layout = QVBoxLayout(right_top_widget)
    right_top_layout.setContentsMargins(0, 0, 0, 0)
    right_top_layout.addWidget(but1)
    right_top_layout.addWidget(but2)
    right_top_layout.addStretch()

    right_top_stack = QStackedLayout()
    right_top_stack.addWidget(right_top_widget)

    left = QTextEdit()
    right = QVBoxLayout()

    # One of these two:
    right.addWidget(right_top_widget)
    # right.addLayout(right_top_stack)

    right.addStretch()
    right.addWidget(but3)

    main_layout = QHBoxLayout(self)
    main_layout.addWidget(left)
    main_layout.addLayout(right)

My problems arise when I put 'right_top_widget' in a StackedLayout.

Without the StackedLayout it looks like this: no stack

And with the StackedLayout it looks like this: with stack

I want it to look like the top picture.

How do you get the StackedLayout to play nice and behave more like a BoxLayout?

P.S. The reason why I want the stackedlayout is not obvious from this example, but I wanted to keep the example simple.

P.P.S. The example is in Python, but answers in C++ are welcome


Solution

  • In this case a possible solution is to set the stretch factor from 1 to QTextEdit and 0 to "right" layout:

    main_layout = QHBoxLayout(self)
    main_layout.addWidget(left, stretch=1)
    main_layout.addLayout(right, stretch=0)