[Kde-bindings] Python Qt4 Newbie

Lauro Moura lauromoura at gmail.com
Wed Aug 20 19:24:47 UTC 2008


On Wed, Aug 20, 2008 at 12:08 PM, Ruben Fonseca <rf at 7syntax.com> wrote:
> Hi,
>
> I'm having a problem developing my first Python Qt4 app and I thought
> you could help me.
>
> I have a bunch of buttons that I want to watch for the "clicked()"
> signal.
>
> Since the handling is the same for all buttons I decided to write
> something like this
>
> ----------
> for button in [self.button_1, self.button_2, ..., self.button_0]:
>   QtCore.QObject.connect(button, QtCore.SIGNAL('clicked()'), lambda:
> self.button_clicked(button))
>
> def button_clicked(self, number):
>   print "Received a signal from %s" % number.objectName()
> ----------
>
> However, every time I click on a button I got on the console
>
> "Received a signal from button_0"
>
> regardless the button I click... So I'm guessing something's wrong with
> my lambda function.
>
> What's the best way of solving this particular problem in Python?

You guessed right, as the lambda is told to 'call button_clicked with
the object identified by the name button *at the time of the call* as
argument'. So, after the loop the name button is still bound to the
last item of that list, thus being passed to each slot.

>>> x = lambda : a*4
>>> x()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <lambda>
NameError: global name 'a' is not defined
>>> a = 3
>>> x()
12
>>>

This is a small thing that I like about GObject signaling system and
miss in Qt, the option to associate a void * to a given connection and
receiving that pointer when that connection is activated.
-- 
Lauro Moura ("lmoura" on Freenode)
http://lauro.wordpress.com



More information about the Kde-bindings mailing list