Parameter passing in signals



  • Hello,

    I was wondering wat the simplest way is to pass parameters with a signal:

    if i (using PySide) have something like:

    @button0.clicked.connect(self.select) #want to call self.select(0)
    button1.clicked.connect(self.select) #want to call self.select(1)
    @

    with:

    @def select(self, index):
    self.selection = self.selectables[index]
    @

    How do i do that, do i need separate methods select0, select1, etc or is there a more structural way?

    Thanks,

    Lars



  • In general, the signal and the slot need to have the same signature (except for default parameters in the slot). So you can't just connect a mySignal(void) to a mySlot(int). The more structural way to solve this is using "QSignalMapper":http://qt-project.org/doc/qt-5.0/qsignalmapper.html , although that also requires a certain amount of boilerplate. Depending on your particular application it may be easier to have a proxy slot that calls select based on sender(). Something like

    @
    button0.clicked.connect(self.intermediary) #want to call self.select(0)
    button1.clicked.connect(self.intermediary) #want to call self.select(1)

    def intermediary():
    select( sender().id() )
    @

    I confess I'm more of a C++ guy, so I don't know if sender() and id() are the exact method signatures, but I hope you get the idea?



  • thanks for te quick reply ..

    can I see id() as an arbitrary number that is equal for each run of the program?



  • id() was just an example, I don't think that function actually exists in QPushButton... sorry, that was a little unclear on my part :)

    If your buttons all have different (and known) names, you could for instance use a dictionary of {"button0name" : 0, "button1name" : 1,...} and do @ select( dictionary[ sender().text() ] ) @

    That's kind of an ugly hack though. You probably want to subclass QPushButton and add a getId(void) and setId(int) function to get/set the button id.



  • For future reference, i solved it somewhat differently, using moritzg's idea:

    In python/PySide you can add attributes dynamically to objects, so ..
    @
    button0.index = 0
    button1.index = 1

    button0.clicked.connect(self.preselect)
    button1.clicked.connect(self.preselect)

    def preselect(self):
    self.select(self.sender().index)

    def select(self, index):
    self.selection = self.selectables[index]

    @

    Be carefull with nameclashes, in this case for 'index'.



  • OK, so it's basically the same idea :-) only in python one can just dynamically add id/index to the object ..


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.