Python Forum
PyQt5 QPushButton Problem
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
PyQt5 QPushButton Problem
#2
It is hard to tell because of the indentation. I am assuming your code looks like this:
from PySide2.QtWidgets import *
class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(100,300)
        layout = QGridLayout()
        for x in range(8):
            for y in range(8):
                self.buttons = QPushButton(self)
                layout.addWidget(self.buttons,x,y)
        self.setLayout(layout)
        self.buttons.clicked.connect(self.flag)

    def flag(self):
        self.buttons.setStyleSheet("background-color : red")

if __name__ == '__main__':
    app = QApplication([])
    window = MainWindow()
    window.show()
    app.exec()
The problem with this code is that only the last button is bound to the "clicked" signal. None of the other buttons have anything to do when pressed.

You need to bind all the buttons to the callback signal. But the obvious solution below does not work.
from PySide2.QtWidgets import *

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(100,300)
        layout = QGridLayout()
        self.setLayout(layout)
        for x in range(8):
            for y in range(8):
                self.buttons = QPushButton(self)
                layout.addWidget(self.buttons,x,y)
                self.buttons.clicked.connect(self.flag)

    def flag(self):
        self.buttons.setStyleSheet("background-color : red")

if __name__ == '__main__':
    app = QApplication([])
    window = MainWindow()
    window.show()
    app.exec()
Now clicking any button calls flag(), but flag only knows about the very last button. The only button saved as an attribute of MainWindow().

What you need to do is somehow tell the callback flag() about which button was pressed. You should do a little research on lambda functions and functools.partial.
Reply


Messages In This Thread
PyQt5 QPushButton Problem - by Hellmut - Dec-26-2020, 07:11 PM
RE: PyQt5 QPushButton Problem - by deanhystad - Dec-26-2020, 07:56 PM
RE: PyQt5 QPushButton Problem - by Hellmut - Dec-26-2020, 08:41 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Math problem in Python - pyqt5 rwahdan 6 5,810 Jun-18-2019, 08:11 PM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020