本文主要介绍如何使用栅格布局,并通过迭代的方式将控件填入栅格布局中
首先,我们先把想要的控件名放入一个列表中:
class Calc(QWidget):
def __init__(self):
super(Calc, self).__init__()
self.setWindowTitle("计算器")
grid = QGridLayout()
self.setLayout(grid)
names = ['Cls', 'Back', '', 'Close',
'7', '8', '9', '/',
'4', '5', '6', '*',
'0', '.', '=', '+']
接下来我们通过循环产生每一个元素所属的列数,行数:
positions = [(i, j) for i in range(5) for j in range(4)]
最后,我们就只需要把控件填入对应的栅格中:
for position, name in zip(positions, names):
if name == "":
continue
button = QPushButton(name)
grid.addWidget(button, *position)
效果如图:

完整代码如下:
import sys
from PyQt5.QtWidgets import *
class Calc(QWidget):
def __init__(self):
super(Calc, self).__init__()
self.setWindowTitle("计算器")
grid = QGridLayout()
self.setLayout(grid)
names = ['Cls', 'Back', '', 'Close',
'7', '8', '9', '/',
'4', '5', '6', '*',
'0', '.', '=', '+']
positions = [(i, j) for i in range(5) for j in range(4)]
for position, name in zip(positions, names):
if name == "":
continue
button = QPushButton(name)
grid.addWidget(button, *position)
if __name__ == "__main__":
app = QApplication(sys.argv)
main = Calc()
main.show()
sys.exit(app.exec_())