Create a grid of buttons using a loop in PyQT4

2019-04-13 08:37发布

问题:

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)

Thank you.

回答1:

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

Here is a minimal example:

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_())

results: