PyQt sending parameter to slot when connecting to a signal

前端 未结 5 1290
青春惊慌失措
青春惊慌失措 2020-12-02 18:37

I have a taskbar menu that when clicked is connected to a slot that gets the trigger event. Now the problem is that I want to know which menu item was clicked, but I don\'t

相关标签:
5条回答
  • 2020-12-02 19:05

    use functools.partial

    otherwise you will find you cannot pass arguments dynamically when script is running, if you use lambda.

    0 讨论(0)
  • 2020-12-02 19:15

    Use a lambda

    Here's an example from the PyQt book:

    self.connect(button3, SIGNAL("clicked()"),
        lambda who="Three": self.anyButton(who))
    

    By the way, you can also use functools.partial, but I find the lambda method simpler and clearer.

    0 讨论(0)
  • 2020-12-02 19:15

    I'd also like to add that you can use the sender method if you just need to find out what widget sent the signal. For example:

    def menuClickedFunc(self):
        # The sender object:
        sender = self.sender()
        # The sender object's name:
        senderName = sender.objectName()
        print senderName
    
    0 讨论(0)
  • 2020-12-02 19:22

    As already mentioned here you can use the lambda function to pass extra arguments to the method you want to execute.

    In this example you can pass a string obj to the function AddControl() invoked when the button is pressed.

    # Create the build button with its caption
    self.build_button = QPushButton('&Build Greeting', self)
    # Connect the button's clicked signal to AddControl
    self.build_button.clicked.connect(lambda: self.AddControl('fooData'))
    def AddControl(self, name):
        print name
    

    Source: snip2code - Using Lambda Function To Pass Extra Argument in PyQt4

    0 讨论(0)
  • 2020-12-02 19:28

    In general, you should have each menu item connected to a different slot, and have each slot handle the functionality only for it's own menu item. For example, if you have menu items like "save", "close", "open", you ought to make a separate slot for each, not try to have a single slot with a case statement in it.

    If you don't want to do it that way, you could use the QObject::sender() function to get a pointer to the sender (ie: the object that emitted the signal). I'd like to hear a bit more about what you're trying to accomplish, though.

    0 讨论(0)
提交回复
热议问题