PyQt QGridLayout is another type of layout.
Normally you’d position widgets (buttons, labels et al) with .move(x,y). Not so with a grid.

It positions widgets in an AxB form. Where A is the number of columns and B the number of rows. Similar to what you’d see in excel.

The QGridLayout is part of PyQt5.QtWidgets.

Related Course:
PyQt Desktop Apps with Python

Example

QGridLayout

You can create a QGridLayout or grid with a single line of code:

1
grid = QGridLayout()

Tell the window to use the grid:

1
win.setLayout(grid)

Widgets can be added to the grid with:

1
grid.addWidget(widget,col,row)

pyqt grid

Grid Example

The code below creates a layout containing a group of buttons. It adds a group of buttons by using a nested for loop.

The key part that creates the grid is:

1
2
3
4
5
6
7
grid = QGridLayout()

for i in range(0,5):
for j in range(0,5):
grid.addWidget(QPushButton(str(i)+str(j)),i,j)

win.setLayout(grid)

The rest of the code simply creates the window. But it’s easy for copy and paste.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QGridLayout, QPushButton
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot

def window():
app = QApplication(sys.argv)
win = QWidget()
grid = QGridLayout()

for i in range(0,5):
for j in range(0,5):
grid.addWidget(QPushButton(str(i)+str(j)),i,j)

win.setLayout(grid)
win.setWindowTitle("PyQt Grid Example")
win.setGeometry(50,50,200,200)
win.show()
sys.exit(app.exec_())

if __name__ == '__main__':
window()

Download Examples