[Qt-interest] connect()ing multiple buttons to a receiver
Brad Howes
howes at ll.mit.edu
Thu Jan 8 16:49:57 CET 2009
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.
> 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
--
Brad Howes
Group 42
MIT Lincoln Laboratory • 244 Wood St. • Lexington, MA 02173
Phone: 781.981.5292 • Fax: 781.981.3495 • Secretary: 781.981.7420
More information about the Qt-interest-old
mailing list