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: Create GUI Apps with Python PyQt5
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)
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
7grid = 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 | import sys |
If you are new to Python PyQt, then I highly recommend this book.