tags:

views:

95

answers:

2

Hello everyone,

I was wondering, once a clicked() is emitted by a button is there any way of finding out what button emitted it without overloading the click() function? (I have a bunch of buttons with almost the same function but different text, which is the defining element of each button).

Thanks in advance!

+5  A: 

You probably want to use a QSignalMapper.

In your case, if it's only the text you are interested in then connect the clicked() signal on each button to the map() slot on your signal mapper and then set a string mapping with setMapping( QObject * sender, const QString & text ). The signal mapper will then re-emit the signal in the form of it's own mapped( const QString & text ) signal with the correct text for the button that was clicked.

Troubadour
In most cases this is the cleaner solution than casting the sender(), it obviates the need for the cast. Also a solution not relying on the sender will work when the slot is not called from a signal
Harald Scheirich
While it's true that QSignalMapper can in many cases be cleaner than sender, the advantage that sender has over QSignalMapper is that you still preserve the parameters the emitted signals send out. For example, when it comes to the QNetworkReply::downloadProgress(qint64, qint64) signal, you cannot access the two qint64 parameters in your slot if you use QSignalMapper, whereas you can still access them if the idiom you use involves sender. But back to what you said, yes, QSignalMapper does have the added benefit of allowing the slot to be called as a normal function.
blwy10
@blwy10: It's true that a raw `QSignalMapper` is limited by the slots it defines but it's not too difficult to extend the functionality if you have arguments you need to get at.
Troubadour
+8  A: 

Within your slot, you can call the sender() function to get the QObject that sent you the clicked() signal. It returns a QObject *. Use qobject_cast to cast the QObject * to QPushButton *.

Documentation here.

blwy10
Exactly what I needed. sender() is great!
Cenoc
Why the 2 downvotes? Was there anything wrong in what I said?
blwy10
@blwy10: I too hate anonymous downvoting so I can assure you it wasn't me. I don't agree with using `sender()` unless it is absolutely necessary but I didn't think it was deserving of a downvote.
Troubadour
I like it, it simplifies the code and increases readability. As long as it continues to be supported, screw conventions, in my opinion. But mapping sounds like a great way of doing it too.
Cenoc