PDA

View Full Version : tip on using QObject::sender()



drhex
3rd April 2008, 18:09
No question this time, but a little tip on using QObject::sender().

In a slot, you can call sender() to get a pointer to the object that called the slot. Previously, I drew two conclusions from this:


you can check if a slot was called directly as a normal C++-method by checking if sender() == NULL

if sender is not NULL, it is safe to cast sender() to Foo * if you know that only objects of type Foo have been connected to this particular slot.


Both turned out to be incorrect :o If an object of type Bar emits a signal that calls slot1, and slot1 then makes a normal function call to slot2() in the same class, then slot2's sender() will be that Bar object even though it was a normal function call and no Bar object is connected to slot2.

wysota
3rd April 2008, 20:01
you can check if a slot was called directly as a normal C++-method by checking if sender() == NULL
This is a false assumption. The docs say behaviour is undefined if you call sender() from within a non-signal call.


if sender is not NULL, it is safe to cast sender() to Foo * if you know that only objects of type Foo have been connected to this particular slot.
If it is your slot (and it's only called as a slot), then that's kind of a safe assumption, but it's better to always use qobject_cast here, just in case.

In general avoid using sender() if possible.