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.

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

And how would you tie these buttons to actions? is it different than what is used for single buttons?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.