[Python] How to cancel the action of a selected button (QPushButton) when a new button is...

Discussão em 'Python' iniciado por Stack, Julho 11, 2025.

  1. Stack

    Stack Membro Participativo

    `class MainWindow(QWidget): def init(self): super().init()

    self.setWindowTitle("Window")
    self.setGeometry(600, 100, 600, 400)

    self.Function()

    def Function(self):
    xpos = 10

    for i in range(5):

    button = QPushButton("".format(i+1), self)
    button.setGeometry(xpos, 150, 50, 50 )
    xpos = xpos + 50
    button.setStyleSheet("border : 1px solid black;background-color : green; border-radius : 25px")
    button.clicked.connect(lambda ch, i=i+1: self.function(i))
    button.clicked.connect(lambda ch, i=button : self.color(i))


    def function(self, i):
    print(i)

    def color(self, i):
    i.setStyleSheet("border : 1px solid black;background-color : black; border-radius : 25px")`i am new to this sort of programming, and


    i am trying to create a row of buttons (number of buttons are given as input) that are aligned side by side. A button (QPushButton) that is once clicked should take on a color, and when an other button is clicked, the previous action should be canceled and the new selected button must be colored.

    I was able to use the "btn.clicked.connect(...)" method to make the selected button get colored. But when the other buttons are clicked the previous ones keep the color without going into default. How do i have to do it correctly?

    Continue reading...

Compartilhe esta Página