Search code examples
pythonqtpyqt

How to use spacers in Qt


I have a QGroupBox with assigned to it QVBoxLayout.

groupBox = QtGui.QGroupBox()
layout = QtGui.QVBoxLayout()
groupBox.setLayout(layout )

Then there is a single QLabel assigned to the layout.

label = QtGui.QLabel()   
layout.addWidget(label)

The problem is that QLabel is positioned at the middle of the GroupBox. While I want it to be aligned with the top edge of the GroupBox. I probably need to add some sort of spacer. So the spacer would dynamically resize itself to fill the GroupBox's empty area pushing QLabel upward.

What widget and what size policy should be used as a spacer?


Solution

  • label = QtGui.QLabel()   
    layout.addWidget(label)
    verticalSpacer = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
    layout.addItem(verticalSpacer)
    

    This should work