Box layout

The box layout class provides a much more flexible and practical layout. ( QBoxLayout official document )

QHBoxLayout and QVBoxLayout are layout classes that sort multiple widgets horizontally and vertically. The QHBoxLayout and QVBoxLayout creators create a horizontal and vertical box, where you can insert other layout boxes or place widgets.

In the example code, use one horizontal and one vertical box to place two buttons at the bottom center of the widget. Let’s use the addStretch() method and adjust the ‘stretch factor’ to create the space you need.


Example

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 the two buttons below the center of the window. The two buttons will stay at the same position regardless of the size of the window.


Description

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

We made two buttons.


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

This addStretch() method provides a flexible empty space. Because the stretch factor on both buttons is equal to 1, the size of these blank spaces is always the same regardless of the window size.


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

Next put the horizontal box(hbox) in the vertical box(vbox). The stretch factor of the vertical box pushes the horizontal box down so that the two buttons are located at the bottom of the window.

The size of the blank spaces above and below the horizontal box will always be 3:1. Changing the stretch factor several times will help you understand better.


self.setLayout(vbox)

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


Results

../_images/3_2_box_layout.png ../_images/3_2_box_layout_mac.png

Figure 4-2. Box layout.


Prev/Next