Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send additional variable during PyQt PushButton click

I'm new to Python and PyQt and this is my first application. Currently when a button is clicked, toggleLED() checks self.LedOn to decide whether to turn an LED on.

class Screen(QWidget):

    def initUI(self):
        self.LedOn = 0

        btn = QPushButton('Off', self)
        btn.setCheckable(True)
        btn.clicked.connect(self.toggleLED)


    def toggleLED(self, pressed):

        source = self.sender()

        if self.LedOn:
            source.setText('Off')
            source.LedOn = 0
            self.serial.write('L')
        else:           
            source.setText('On')
            source.LedOn = 1
            self.serial.write('H')

Problem: Now if we want to control multiple LEDs and remember their individual toggle state, what is the best practice?

I also cant seem to pass an additional value to toggleLED() with btn.clicked.connect(self.toggleLED(btnNumber))

class Screen(QWidget):

    def initUI(self):

        btn1 = QPushButton('Off', self)
        btn1.setCheckable(True)
        btn1.LedOn= 0
        btn1.clicked.connect(selftoggleLED(1))

        btn2 = QPushButton('Off', self)
        btn2.setCheckable(True)
        btn2.LedOn= 0
        btn2.clicked.connect(selftoggleLED(2))


    def toggleLED(self, pressed, value):

        source = self.sender()

        if self.LedOn:
            source.setText('Off')
            self.serial.write(value)
            self.serial.write('L')
        else:           
            source.setText('On')
            self.serial.write(value)
            self.serial.write('H')
like image 639
Nyxynyx Avatar asked Dec 21 '22 00:12

Nyxynyx


1 Answers

You can use partial for that:

from functools import partial

btn1.clicked.connect(partial(self.toggleLED, 1))

This allows you to pass multiple arguments to a function.

like image 73
Achayan Avatar answered Dec 31 '22 13:12

Achayan