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

Oliver.Knoll at comit.ch Oliver.Knoll at comit.ch
Thu Jan 8 09:17:03 CET 2009


Malyushytsky, Alex wrote on Wednesday, January 07, 2009 11:32 PM:

> ...
> If this slot can be invoked only from clicking on QButton you could:
>
> if ( sender() )
> {
> QButton* b = (QButton*) sender();
>  .....
>
> }

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."

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).

QSignalMapper seems to be a bit more cumbersome, but it makes it explicit what you are actually trying to achieve. And it works with *any* sender (as long as you assign them unique IDs). The other solution which has been proposed (using QButtonGroup) is basically the same idea: it is a "QSignalMapper specialised for QAbstractButtons".

  http://doc.trolltech.com/4.4/qbuttongroup.html#addButton-2
  http://doc.trolltech.com/4.4/qbuttongroup.html#buttonClicked-2


Cheers, Oliver
--
Oliver Knoll
Dipl. Informatik-Ing. ETH
COMIT AG - ++41 79 520 95 22




More information about the Qt-interest-old mailing list