IgnisNoctum
IgnisNoctum

Reputation: 43

How to get a PyQt5 QPushButton to do different commands on different button clicks

I wish to have the QPushButton do different things on different clicks. One the first click it should execute one command and on the next click, it should execute the other command. I've tried to make a program to do it but it only executes one command, not the other

my code I:

import PyQt5.QtWidgets as pyqt
import sys

ongoing = False


class Stuff(pyqt.QWidget):
    def __init__(self):
        super().__init__()
        self.windows()

    def windows(self):
        w = pyqt.QWidget()
        layout = pyqt.QGridLayout()
        self.setLayout(layout)
        
        button = pyqt.QPushButton('click me', w)
        layout.addWidget(button)

        if not ongoing:
            button.clicked.connect(click_one)
        else:
            button.clicked.connect(click_two)
        self.show()
        w.show()


def click_one():
    global ongoing
    print('one')
    ongoing = not ongoing


def click_two():
    global ongoing
    print('two')
    ongoing = not ongoing


if __name__ == '__main__':
    app = pyqt.QApplication(sys.argv)
    x = Stuff()
    app.exec_()

What should I do to fix this?

Upvotes: 0

Views: 743

Answers (1)

alec
alec

Reputation: 6112

Since the value of ongoing is False when the class is initialized, the button's clicked signal gets connected to click_one(). Connect the button to an initial slot and then call the desired function based on the value of ongoing.

class Stuff(pyqt.QWidget):
    def __init__(self):
        super().__init__()
        self.windows()

    def windows(self):
        w = pyqt.QWidget()
        layout = pyqt.QGridLayout()
        self.setLayout(layout)
        
        button = pyqt.QPushButton('click me', w)
        layout.addWidget(button)

        button.clicked.connect(on_click)
        self.show()
        w.show()

def on_click():
    global ongoing
    if not ongoing:
        click_one()
    else:
        click_two()

I suggest rewriting the code with the functions and ongoing variable belonging to the class. The QWidget assigned to variable w seems redundant because the QPushButton is then added to the layout of the class, so its parent gets changed anyways.

class Stuff(pyqt.QWidget):
    
    def __init__(self):
        super().__init__()
        self.ongoing = False
        self.windows()

    def windows(self):
        layout = pyqt.QGridLayout(self)
        button = pyqt.QPushButton('click me')
        layout.addWidget(button)
        button.clicked.connect(self.on_click)
        self.show()

    def on_click(self):
        self.click_one() if not self.ongoing else self.click_two()
        self.ongoing = not self.ongoing

    def click_one(self):
        print('one')

    def click_two(self):
        print('two')

Also you might be interested in using a checkable button.

Upvotes: 1

Related Questions