在 PyQT4 中使用循环创建按钮网格

2022-01-18 00:00:00 python pyqt button pyqt4 grid

问题描述

有没有办法在 PyQT4 中使用循环创建按钮网格?

Is there a way to create a grid of buttons using a loop in PyQT4?

例如,具有以下效果的东西:

So for example, something that has the effect of:

for j in range(0, 10):
    for k in range(0, 10):
        grid.addbutton(j, k)

谢谢.


解决方案

当然有.QGridLayout 可能有用在这种情况下.

Sure there is. QGridLayout might be useful in this case.

这是一个最小的例子:

import sys
from PyQt4 import QtGui

app = QtGui.QApplication(sys.argv)
widget = QtGui.QWidget()
layout = QtGui.QGridLayout()

buttons = {}

for i in range(10):
    for j in range(10):
        # keep a reference to the buttons
        buttons[(i, j)] = QtGui.QPushButton('row %d, col %d' % (i, j))
        # add to the layout
        layout.addWidget(buttons[(i, j)], i, j)

widget.setLayout(layout)
widget.show()
sys.exit(app.exec_())

结果:

相关文章