Search code examples
pythonpython-3.xpyqtpyqt4

Buttons that update labels in a grid for each respective row


I have a QGrid with 2 columns and 3 rows. The first column consists of QPushButtons's and the second column consists of QLabel's. The buttons => ["This Button", "That Button", "A Button"]. All the labels start at the text 0. Pressing the button in a row should change the text (number) of the label in that same row by adding 1.

The above is a simplified version of the problem, where in reality I have 10+ rows, and 5+ columns.

How would I create all of these rows and columns in a grid with as little code as possible? And how would I link each button to it's respective label without having to create a function for each separate button?


Solution

  • There are several ways to solve it, I will show some:

    1. lambda functios:

    class Widget(QWidget):
        def __init__(self, *args, **kwargs):
            QWidget.__init__(self, *args, **kwargs)
            lay = QGridLayout(self)
            for i in range(3):
                btn = QPushButton("button-{}".format(i), self)
                lbl = QLabel("{}".format(0))
                lay.addWidget(btn, i, 0)
                lay.addWidget(lbl, i, 1)
                btn.clicked.connect(lambda checked, l=lbl: self.fun(l))
    
        def fun(self, lbl):
            n = int(lbl.text()) + 1
            lbl.setText(str(n))
    
    1. dictionary

    class Widget(QWidget):
        def __init__(self, *args, **kwargs):
            QWidget.__init__(self, *args, **kwargs)
            lay = QGridLayout(self)
            self.connections = {}
            for i in range(3):
                btn = QPushButton("button-{}".format(i), self)
                lbl = QLabel("{}".format(0))
                lay.addWidget(btn, i, 0)
                lay.addWidget(lbl, i, 1)
                self.connections[btn] = lbl
                btn.clicked.connect(self.fun)
    
        def fun(self):
            lbl = self.connections[self.sender()]
            n = int(lbl.text()) + 1
            lbl.setText(str(n))