2

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.

KeyPick
  • 103
  • 1
  • 2
  • 5

1 Answers1

8

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:

QGridLayout

Avaris
  • 35,883
  • 7
  • 81
  • 72