Home > Net >  PyQt5 - how to know which of the button is pressed
PyQt5 - how to know which of the button is pressed

Time:08-17

I am creating a GUI that needs to look like a grid. It has 900 button that are created in a loop. Is there any way to determine which of the button was pressed?

    for i in range(30):
        for j in range(30):
            button = QPushButton()
            layout.addWidget(button, i, j)

So for example if a button is pressed on 25th row and 13th column I want to have a function that would print that the button (25,13) was clicked.

CodePudding user response:

You could use QObject::ObjectName. This would allow you to set a name as a string for every button. Then you can connect every button to a slot that does something with that information.

Your code could look something like this. Note: This code is untested.

def makeButtons(self):
    for i in range(30):
        for j in range(30):
            button = QPushButton()
            button.clicked.connect(self.someSlot)
            layout.addWidget(button, i, j)

def someSlot(self):
    name = self.sender().objectName()
    print(name)

CodePudding user response:

Depending on your needs, you can also use QButtonGroup. It makes signal handling easier and has a custom ID per button.

Something like this:

def makeButtons(self):
    n = m = 30
    self.group = group = QButtonGroup()
    group.exclusive = False
    for i in range(n):
        for j in range(m):
            button = QPushButton()
            id = i * m   j
            group.addButton(button, id)
    group.idClicked.connect(self.onIdClicked)

def onIdClicked(self, id):
    row, col = divmod(id, 30)
  • Related