PyQt Grid layout

The most common layout class in Python PyQt5 is the grid layout. This layout class separates the space in the widget by rows and columns. Use the QGridLayout class to create grid layouts.

qgridlayout python pyqt

For the example dialog above, we have divided it into three rows and five columns, and placed the widget where it is needed.

Related course: Create Desktop Apps with Python PyQt5

Grid layout

import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QGridLayout, QLabel, QLineEdit, QTextEdit)

class MyApp(QWidget):

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

    def initUI(self):
        grid = QGridLayout()
        self.setLayout(grid)

        grid.addWidget(QLabel('Title:'), 0, 0)
        grid.addWidget(QLabel('Author:'), 1, 0)
        grid.addWidget(QLabel('Review:'), 2, 0)

        grid.addWidget(QLineEdit(), 0, 1)
        grid.addWidget(QLineEdit(), 1, 1)
        grid.addWidget(QTextEdit(), 2, 1)

        self.setWindowTitle('QGridLayout')
        self.setGeometry(300, 300, 300, 200)
        self.show()

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

We've placed three labels, two line editors, and one text editor in grid form.

Description

grid = QGridLayout()
self.setLayout(grid)

Create a QGridLayout and set it to the layout of the application window.

grid.addWidget(QLabel('Title:'), 0, 0)
grid.addWidget(QLabel('Author:'), 1, 0)
grid.addWidget(QLabel('Review:'), 2, 0)

The first widget in the addWidget() method is the widget you want to add, and the second and third widgets enter a row and column number, respectively. Place the three labels perpendicular to the first column.

grid.addWidget(QTextEdit(), 2, 1)

The QTextEdit() widget is a widget that allows you to modify multiple lines of text, unlike the QLineEdit() widget. Place in the third row, the second column.

Related course: Create Desktop Apps with Python PyQt5