Search code examples
pythonpyqtpyqt5

How do I modify spacing in nested PyQt layouts?


Currently, I have a nested QVBoxLayout in the first column of a QHBoxLayout, but no matter my changes to .setContentMargins or .setSpacing nothing changes in that first column.

import sys
import io
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import QWebEngineView

class MyApp(QWidget):
    def __init__(self):
        super().__init__()
        # Main widget/window
        self.setWindowTitle('Test')
        self.window_width, self.window_height = 1600, 900
        self.setMinimumSize(self.window_width, self.window_height)

        layout = QHBoxLayout()
        self.setLayout(layout)

        leftside = QWidget()
        leftlayout = QVBoxLayout()

        # Creating textbox and adding to leftside GUI
        lineEdit = QLineEdit()
        leftlayout.addWidget(lineEdit)
        leftlayout.addWidget(QPushButton('Placeholder'))
        leftside.setLayout(leftlayout)

        # Adding both widgets to main layout
        testWidget = QWidget()
        testWidget.setStyleSheet("background-color: blue")
        layout.addWidget(leftside, 2)
        layout.addWidget(testWidget, 8)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setStyleSheet('''
        QWidget {
            font-size: 20px;
        }
    ''')

    myApp = MyApp()
    myApp.show()

    try:
        sys.exit(app.exec_())
    except SystemExit:
        print('Closing Window...')

Leaves me with this result: Current result

What I want: enter image description here


Solution

  • Use addStretch() method:

    class MyApp(QWidget):
        def __init__(self, parent=None):
            super().__init__(parent)
            self.setWindowTitle("Test")
            self.window_width, self.window_height = 1600, 900
            self.setMinimumSize(self.window_width, self.window_height)
    
            leftside = QWidget()
            leftlayout = QVBoxLayout(leftside)
            lineEdit = QLineEdit()
            leftlayout.addWidget(lineEdit)
            leftlayout.addWidget(QPushButton("Placeholder"))
            leftlayout.addStretch()
    
            testWidget = QWidget()
            testWidget.setStyleSheet("background-color: blue")
    
            layout = QHBoxLayout(self)
            layout.addWidget(leftside)
            layout.addWidget(testWidget, stretch=1)