Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyQt sending parameter to slot when connecting to a signal

Tags:

python

qt4

pyqt

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 know how to send that information to the function connected to. Here is the used to connect the action to the function:

QtCore.QObject.connect(menuAction, 'triggered()', menuClickedFunc)

I know that some events return a value, but triggered() doesn't. So how do I make this happen? Do I have to make my own signal?

like image 282
johannix Avatar asked Jun 02 '09 16:06

johannix


4 Answers

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.

like image 194
Eli Bendersky Avatar answered Oct 17 '22 08:10

Eli Bendersky


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

like image 42
Dominique Terrs Avatar answered Oct 17 '22 08:10

Dominique Terrs


use functools.partial

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

like image 4
Eric Wang Avatar answered Oct 17 '22 07:10

Eric Wang


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
like image 4
shalinar Avatar answered Oct 17 '22 07:10

shalinar