[Qt-interest] connect()ing multiple buttons to a receiver

Scott Aron Bloom Scott.Bloom at sabgroup.com
Thu Jan 8 18:02:20 CET 2009


> -----Original Message-----
> From: qt-interest-bounces at trolltech.com [mailto:qt-interest-
> bounces at trolltech.com] On Behalf Of Brad Howes
> Sent: Thursday, January 08, 2009 7:50 AM
> To: qt-interest
> Subject: Re: [Qt-interest] connect()ing multiple buttons to a receiver
> 
> On Jan 8, 2009, at 3:17 AM, Oliver.Knoll at comit.ch wrote:
> 
> > While this works in practice it is dangerous and for good reason the
> > Qt docs discourage you to use the sender() method:
> >
> > http://doc.trolltech.com/4.4/qobject.html#sender
> > "Warning: This function violates the object-oriented principle of
> > modularity. However, getting access to the sender might be useful
> > when many signals are connected to a single slot."
> 
> Discourage? Their 'however' clause covers the very scenario that was
> brought up.


And of course... sender() is USED by QSignalMapper :)

> 
> > Imagine what would happen if anyone would connect any *other*
> > object's signal (other than from a QButton!) to your slot: Your code
> > above would miserably die with an invalid cast. In your slot you
> > *implicitly* assume that *every* sender is a QButton (again, in
> > practice for quick'n'dirty code this assumption is often okay).
> 
> The code should have used qobject_cast<> or dynamic_cast<> followed by
> a NULL check. Nothing scrary.
> 
>      QButton* b = dynamic_cast<QButton*>( sender() );
>      if ( b ) {
>          ...
>      }
> 
> I use this idiom all the time for a "Recent File" menu that maintains
> a dynamic list of QAction items with file names/paths, all connected
> to just one openRecentFile() slot.
> 
> Brad

Using sender CAN be dangerous, not IS dangerous. If you take the proper
precautions, like qobject_cast/dynamic_cast and checking if the method
was called by a non-slot (check for null)

However, QSignalMapper was designed to no longer make that paradigm
necessary...

Scott




More information about the Qt-interest-old mailing list