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(QWi
Solution 1:
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.
Solution 2:
To pass multiple arguments to a function, you can use either functools.partial()
or a lambda
:
btn2.clicked.connect(lambda: selftoggleLED(2))
Read the discussion of both methods.
Solution 3:
Here is the solution that I always use for this job.
classScreen(QWidget):
definitUI(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# I am adding these lines-----------------------# put all the btns in a list
btns = [btn1, btn2]
# connect each btn with the function and pass the same btnmap(lambda btn: btn.clicked.connect(lambda pressed: self.toggleLED(pressed, btn)), btns)
deftoggleLED(self, pressed, clikedBtn):
if pressed:
clickedBtn.setText("On")
# set other variables you needelse:
clickedBtn.setText("Off")
# set other variables
Solution 4:
class Screen(QWidget):
def initUI(self):
btn1 = QPushButton('Off', self)
btn1.setCheckable(True)
btn1.value = 1
btn1.clicked.connect(selftoggleLED)
btn2 = QPushButton('Off', self)
btn2.setCheckable(True)
btn2.value = 2
btn2.clicked.connect(selftoggleLED)
def toggleLED(self, pressed):
source = self.sender()
if pressed:
source.setText('Off')
self.serial.write(source.value)
self.serial.write('L')
else:
source.setText('On')
self.serial.write(source.value)
self.serial.write('H')
- The checkable QPushButton will store the state, so you don't need
btn.LedOn
. - Use
btn.value
to store the btn number, so you don't need to send the extra arg.
Solution 5:
QPushButton
does already have checked
boolean property, so you don't need to create another one. There are two signals which button emits:
clicked
when it's pressedtoggled
when its state is changed
Both of them transfer parameter which indicates a button's state. But I think, the second is more appropriate because of its name.
So the toggleLED
slot should looks like this:
def toggleLED(self, checked):
source = self.sender()
if checked:
source.setText('Off')
self.serial.write('L')
else:
source.setText('On')
self.serial.write('H')
Notice that only checkable buttons emit toggled
signal, but you already set this property in your code:
definitUI(self):
btn1 = QPushButton('Off', self)
btn1.setCheckable(True)
btn1.toggled.connect(self.toggleLED)
btn2 = QPushButton('Off', self)
btn2.setCheckable(True)
btn2.toggled.connect(self.toggleLED)
Post a Comment for "Send Additional Variable During Pyqt Pushbutton Click"