PyQt - slots with parameter
Example:
I have three pushbuttons, all makes almost the same. I want to have only 1 slot-function for all 3开发者_Python百科 buttons.
def slotButtons(nr_button):
#common part
if(nr==1):
#for button 1
else if(nr==2):
#for button 2
else if(nr==3):
#for button 3
#common part
So I need something like slots with parameter..
QtCore.QObject.connect(pushButton1, QtCore.SIGNAL("clicked()"), slotButtons(1))
QtCore.QObject.connect(pushButton2, QtCore.SIGNAL("clicked()"), slotButtons(2))
QtCore.QObject.connect(pushButton3, QtCore.SIGNAL("clicked()"), slotButtons(3))
Can Python(pyQt) do something that?
What connect
needs is any callable Python object. Since Python has functions as first-class objects, this is easy to implement with a wrapper function. For simple cases, a lambda
would do:
self.connect(pyuic4Button, SIGNAL("clicked()"),
lambda: self.setPath("pyuic4"))
self.connect(pyrcc4Button, SIGNAL("clicked()"),
lambda: self.setPath("pyrcc4"))
You can use QObject::sender()
function to behave differently for each sender, object, see QObject documentation for details.
I don't use PyQt but take a look at QSignalMapper documentation, it should be the same. Basically, it allows you to map signals coming from different objects to a slot with a parameter.
You could have a member variable to identify the object and do something like the following im sure.
def slotButtons(btn):
if btn.who_are_you == 1:
# Do some stuff
elif btn.who_are_you == 2:
# Do some stuff
elif btn.who_are_you == 3:
# Do some stuff
# Common part
You can even do :
lambda value: self.doStuff(True if value==True else False)
Its quite great tool once you figure out how it works.
Edit: You can also skip doing all the ifs/else... Just go straight to point... - rough example:
btn_01 = lambda: self.doStuff("C://")
btn_02 = lambda: self.doStuff("D://")
def doStuff(self,dir):
saveFile(dir+"filename.txt")
精彩评论