[PyKDE] Is QObject.sender() working ?

Greg Green gregory.p.green at boeing.com
Fri May 18 23:59:54 BST 2001


Looking at the Qt documentation:

--------------------------------------------------------------------
Returns a pointer to the object that sent the signal, if called in a
slot before any function call or signal emission. Returns an
undefined value in all
other cases.

Warning: This function will return something apparently correct in
other cases as well. However, its value may change during any
function call,
depending on what signal-slot connections are activated during that
call. In Qt 3.0 the value will change more often than in 2.x.

Warning: This function violates the object-oriented principle of
modularity, However, getting access to the sender might be practical
when many
signals are connected to a single slot. The sender is undefined if
the slot is called as a normal C++ function.
---------------------------------------------------------------------

I suspect the last sentence is the problem. Looking at the PyQt code
shows the sender function getting called after some other things. I
would just hook each button up to a separate slot, ugly, but it will
work.

> Sorry if this as already been reported.
> 
> Look at this little code :
> class MyWidget(qt.QWidget):
>     def __init__ (self, *args):
>         apply (qt.QWidget.__init__, (self,)+args)
>         self.vbox = qt.QVBoxLayout(self)
>         # Create two buttons
>         self.bt1 = qt.QPushButton("Button 1", self) ;
>         self.bt2 = qt.QPushButton("Button 2", self) ;
>         # Print button references
>         print "Button 1:", self.bt1
>         print "Button 2:", self.bt2
>         # Add them in the layout
>         self.vbox.addWidget(self.bt1)
>         self.vbox.addWidget(self.bt2)
>         # Connect both buttons to the same slot
>         self.connect(self.bt1, qt.SIGNAL("clicked()"), self.Clicked)
>         self.connect(self.bt2, qt.SIGNAL("clicked()"), self.Clicked)
>         
>     def Clicked(self):
> 	obj = self.sender()
>         print "-- Button clicked:", self.sender()
>             
> And here's a sample output, where I clicked both buttons :
> [yves at kafka ConfiMake]$ ./test.py
> Button 1: <qt.QPushButton instance at 0x82eb92c>
> Button 2: <qt.QPushButton instance at 0x82efbcc>
> -- Button clicked: None
> -- Button clicked: None
> 
> So : the QObject.sender() function seems to return always "None".

-- 

Greg Green
Advanced Design Systems
Math & Computing Technology
Boeing
(425) 865-2790





More information about the PyQt mailing list