2

I want to connect a trigger generated from PushButton to my custom signal with an argument(Signal(int)).

It is possible to connect a signal without an argument to the Button. Currently, I am creating an extra slot to emit the Signal(int) triggered from Signal() and Button. Is there any simple way to this?

class GUI(QObject):

sig_x = Signal()
sig_y = Signal(int)

def __init__(self,parent = None):
    super(GUI,self).__init__(parent)
    self.value = 10

    self.button = QPushButton("Click me")   
    self.button.clicked.connect(self.sig_x) 
    #self.button.clicked.connect(self.sig_y(self.value))  want to do something like this
    
    self.sig_x.connect(self.pass_args)
    self.sig_y.connect(self.final_function)

#connection slot for sig_x
def pass_args(self):                                                                                     
    self.sig_y.emit(self.value)  

#demo connection slot for sig_y 
def final_function(self,passed_value):
    print("passed value is " + str(passed_value))
P Sijan
  • 21
  • 3

1 Answers1

1

The reason this won't work:

self.button.clicked.connect(self.sig_y(self.value))

is because connect() needs to be passed a function (or, more precisely anything that can be called). But written like this, you're not passing it the signal itself, you're calling the signal and passing in the result.

One solution is a lambda function. A lambda is a way to define a function inline; this way you define a new function right there, in the same line where you pass it to connect.

self.button.clicked.connect(lambda x: self.sig_y(self.value))

You can see some more context of how this works in this quesiton, even though the question itself is about getting a slightly more complex version to work.


This is all assuming that you need this signal structure for reasons not immediately evident in your example. If not, you could simply connect the button clicked signal directly to your final_function, with no need for custom signals.

class GUI(QObject):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.value = 10

        self.button = QPushButton("Click me")   
        self.button.clicked.connect(self.final_function)

    def final_function(self, state):
        print(f"My value is {self.value}.")

And even then, if you need a signal for notifying other things, you could also add that to the method:

    def final_function(self, state):
        print(f"My value is {self.value}.")
        self.sig_y.emit(self.value)
CrazyChucky
  • 3,263
  • 4
  • 11
  • 25