PDA

View Full Version : Passing values to custom 'slot' functions (pyqt)



Richie
6th September 2009, 20:16
Hi,

Can I first say thanks to all who read my newb questions and helped me out, much appreciated.

Quick pyqt question:

mywindow has a button on it. I want to run the clicked_function when clicked. This works

QtCore.QObject.connect(mywindow.somebutton, QtCore.SIGNAL("clicked()"), clicked_function)


But if I want to click the button and pass 'foo' to the clicked_function, I thought I would be able to use

QtCore.QObject.connect(mywindow.somebutton, QtCore.SIGNAL("clicked()"), clicked_function('foo'))


This brings up an 'argument of incorrect type' error. So how can I pass a value to the function? I thought I might try...


QtCore.QObject.connect(mywindow.somebutton, QtCore.SIGNAL("clicked()"), pre_clicked_function)

def pre_clicked_function():
clicked_function('foo')


But this is far from streamlined! Any better ideas?

hkvm
6th September 2009, 20:30
Hi!

Use functools.partial (http://docs.python.org/library/functools.html), it can take a function and "pre-fill" some or all its arguments, like this:

import functools
#...
self.connect(mywindow.somebutton, SIGNAL("clicked()"), functools.partial(clicked_function, "foo"))

mayowa
7th September 2009, 07:05
Hi,

Another way to do this would be to use lambda:


self.connect(mywindow.somebutton, SIGNAL("clicked()"), (lambda p="foo" : clicked_function(p)))