Results 1 to 2 of 2

Thread: tip on using QObject::sender()

  1. #1
    Join Date
    Jan 2006
    Location
    Knivsta, Sweden
    Posts
    153
    Thanks
    30
    Thanked 13 Times in 12 Posts
    Qt products
    Qt4 Qt5
    Platforms
    Unix/X11

    Lightbulb tip on using QObject::sender()

    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:

    1. you can check if a slot was called directly as a normal C++-method by checking if sender() == NULL
    2. 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 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.

  2. #2
    Join Date
    Jan 2006
    Location
    Warsaw, Poland
    Posts
    33,363
    Thanks
    3
    Thanked 5,012 Times in 4,791 Posts
    Qt products
    Qt3 Qt4 Qt5 Qt/Embedded
    Platforms
    Unix/X11 Windows Android Maemo/MeeGo
    Wiki edits
    10

    Default Re: tip on using QObject::sender()

    Quote Originally Posted by drhex View Post
    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.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.