PyQt5 - QGridLayout Class



A GridLayout class object presents with a grid of cells arranged in rows and columns. The class contains addWidget() method. Any widget can be added by specifying the number of rows and columns of the cell. Optionally, a spanning factor for row as well as column, if specified makes the widget wider or taller than one cell. Two overloads of addWidget() method are as follows −

Sr.No. Methods & Description
1

addWidget(QWidget, int r, int c)

Adds a widget at specified row and column

2

addWidget(QWidget, int r, int c, int rowspan, int columnspan)

Adds a widget at specified row and column and having specified width and/or height

A child layout object can also be added at any cell in the grid.

Sr.No. Methods & Description
1

addLayout(QLayout, int r, int c)

Adds a layout object at specified row and column

Example

The following code creates a grid layout of 16 push buttons arranged in a grid layout of 4 rows and 4 columns.

import sys 
from PyQt5.QtCore import * 
from PyQt5.QtGui import * 
from PyQt5.QtWidgets import *

def window():
   app = QApplication(sys.argv)
   win = QWidget()
   grid = QGridLayout()
	
   for i in range(1,5):
      for j in range(1,5):
         grid.addWidget(QPushButton("B"+str(i)+str(j)),i,j)
			
   win.setLayout(grid)
   win.setGeometry(100,100,200,100)
   win.setWindowTitle("PyQt")
   win.show()
   sys.exit(app.exec_())

if __name__ == '__main__':
   window()

The code uses two nested for loops for row and column numbers, denoted by variables i and j. They are converted to string to concatenate the caption of each push button to be added at ith row and jth column.

The above code produces the following output −

QGridLayout Class Output
pyqt_layout_management.htm
Advertisements