📅  最后修改于: 2023-12-03 15:01:04.665000             🧑  作者: Mango
GridLayout is a layout manager in PyQt5 that arranges widgets in a grid. It is a very useful layout manager, especially when you need to arrange a large number of widgets. In this tutorial, we will learn how to use GridLayout in PyQt5 with the help of for loop.
To use GridLayout in PyQt5, we need to install the PyQt5 library. You can install it using pip.
pip install PyQt5
from PyQt5.QtWidgets import QApplication, QWidget, QGridLayout, QLabel
app = QApplication([])
window = QWidget()
layout = QGridLayout()
for i in range(5):
for j in range(5):
label = QLabel(f"{i},{j}")
layout.addWidget(label, i, j)
window.setLayout(layout)
window.show()
app.exec_()
We start by importing the necessary classes from PyQt5. We then create an instance of QApplication and a QWidget that will serve as our window. We create a QGridLayout and assign it to our window.
We use two nested for loops to create 25 QLabel widgets. We set the text of each label to its respective row and column number. We use the addWidget method to add each label to the grid layout. The first argument of addWidget is the widget to add, while the second and third arguments are the row and column positions in the grid.
We set the grid layout as the layout of our window and display it.
In this tutorial, we learned how to use GridLayout in PyQt5 using for loop. GridLayout is a powerful layout manager that makes the task of arranging widgets in a grid extremely easy.