We’re going to introduce the
QBox layout like a horizontal box layout, a vertical box layout and the stretch widgets.
Vertical Box Layout -
b = QtWidgets.QPushButton('Click!') l = QtWidgets.QLabel('Label Example')
QLabel are not added to the window the same as what we did in last chapters. These two widgets would be added to the box layout later.
v_box = QtWidgets.QVBoxLayout()
It creates a vertical box layout -
QVBoxLayout that the widgets added to this layout will be aligned vertically where firstly added widget is on top of other widgets.
It doesn’t do anything at the moment because it’s just a container where we’re going to put our widgets.
It adds the button and label to the vertical box layout
If we run this code, we will get the push button and the label one underneath the other.
If you change the window size, you will see that these two widgets are not aligned any more.
We will change our code to make it look better.
Horizontal Box -
h_box = QtWidgets.QHBoxLayout()
It creates a horizontal box layout.
h_box.addStretch() h_box.addWidget(labelA) h_box.addStretch()
addStretch() widget fills up as much space horizontally as it can. Two stretches before and after the label take up as much space as need to leave the label right in the middle of the horizontal box.
Horizontal Alignment Center
Another way to align the widget in the center is set the alignment of the widget to be
It only adds two lines compared to the first example above,
setAlignment method sets the alignment of the widget and
QtCore.Qt.AlignCenter is the center alignment parameters from
QtCore module that should be imported to the code.
It has exactly the same layout with the example above.