Learn Python PyQt

PyQt Box layout

Layout management uses layout classes in a more flexible and practical way. QHBoxLayout and QVBoxLayout are the basic layout classes for horizontal and vertical alignment controls, respectively.

Imagine that we want to put two buttons in the lower right corner of the program. To create such a layout, we can use two boxes, one horizontal and one vertical. To create the necessary free space, we will add a stretch factor.

Book: Create Desktop Apps with Python PyQt5

QBoxLayout example

The example below creates a QHBoxLayout and a QVBoxLayout, it uses that to add buttons.

box layout
import sys
from PyQt5.QtWidgets import (QApplication, QWidget,
  QPushButton, QVBoxLayout, QHBoxLayout)

class Example(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)
        vbox = QVBoxLayout()
        vbox.addStretch(1)
        vbox.addLayout(hbox)
        self.setLayout(vbox)
        self.setGeometry(300, 300, 350, 150)
        self.setWindowTitle('Box layout example, QHBoxLayout, QVBoxLayout')  
        self.show()

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

Code Analysis
This example places the two buttons in the lower right corner of the window. When we resize the app window, they are fixed in the lower right corner. We use both HBoxLayout and QVBoxLayout layouts.

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

We have created two buttons.

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

We created a horizontal box layout, added the stretch factor (addStretch) and added (addWidget) two buttons.

A stretch factor was added before adding the two buttons, which will push the two buttons to the right side of the window.

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

To get the layout we want, we also need to put the horizontal layout into the vertical layout. The stretch factor on the vertical box pushes the horizontal box including the controls inside to the bottom of the window.

self.setLayout(vbox)

Finally, we set the main layout of the window.