PyQt - Box layout

Box layout classes allow for more flexible and practical layouts. QHBoxLayout, QVBoxLayout is a layout class that arranges multiple widgets horizontally.

The QHBoxLayout, QVBoxLayout constructor creates one horizontal and vertical box, which you can put in another layout box or place a widget.

Related course: Create Desktop Apps with Python PyQt5

Box layout

In the example code, use horizontal and vertical boxes one by one to place two buttons in the lower center of the widget.

To create the space we need, we're using the addStretch() method, and adjusting the 'stretch factor'.

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QHBoxLayout, QVBoxLayout

class MyApp(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        okButton = QPushButton('OK')
        cancelButton = QPushButton('Cancel')

        hbox = QHBoxLayout()
        hbox.addStretch(1)
        hbox.addWidget(okButton)
        hbox.addWidget(cancelButton)
        hbox.addStretch(1)

        vbox = QVBoxLayout()
        vbox.addStretch(3)
        vbox.addLayout(hbox)
        vbox.addStretch(1)

        self.setLayout(vbox)

        self.setWindowTitle('Box Layout')
        self.setGeometry(300, 300, 300, 200)
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MyApp()
    sys.exit(app.exec_())

Place two buttons under the center of the window. The two buttons are in the same position even if you change the size of the window.

box layout pyqt

Description

okButton = QPushButton('OK')
cancelButton = QPushButton('Cancel')

I created two buttons.

hbox = QHBoxLayout()
hbox.addStretch(1)
hbox.addWidget(okButton)
hbox.addWidget(cancelButton)
hbox.addStretch(1)

Create one horizontal box, add two buttons and an empty space on both side. This addStretch() method provides elastic empty space.

Because the stretch factors on both sides of the button are equal to 1, the size of these two empty spaces is always the same even if the size of the window changes.

vbox = QVBoxLayout()
vbox.addStretch(3)
vbox.addLayout(hbox)
vbox.addStretch(1)

Next, place the horizontal box (hbox) in the vertical vbox. The stretch factor in the vertical box pushes the horizontal box downwards so that the two buttons are positioned at the bottom of the window.

Even at this time, the size of the empty space above and below the horizontal box always maintains 3:1. By varying the stretch factor, you can understand the meaning well.

self.setLayout(vbox)

Finally, set the vertical box to the main layout of the window.

Related course: Create Desktop Apps with Python PyQt5