2

Example:

I have three pushbuttons, all makes almost the same. I want to have only 1 slot-function for all 3 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?

Meloun
  • 13,601
  • 17
  • 64
  • 93
  • QtCore.QObject.connect(pushButton1, QtCore.SIGNAL("clicked()"), lambda : slotButtons(1)) I've tried this, it works. – Meloun Jan 10 '11 at 12:17

5 Answers5

5

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"))
Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412
1

You can use QObject::sender() function to behave differently for each sender, object, see QObject documentation for details.

ismail
  • 46,010
  • 9
  • 86
  • 95
0

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")
Dariusz
  • 960
  • 13
  • 36
0

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.

erelender
  • 6,175
  • 32
  • 49
0

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
zrbecker
  • 1,394
  • 1
  • 19
  • 39