[Qt-interest] Bug? sender() is always NULL when receiver lives in different QThread from emitter

Sean Harmer sean.harmer at maps-technology.com
Mon Jul 6 16:23:16 CEST 2009


Hi,

On Monday 06 Jul 2009 15:07:47 Florian Vichot wrote:
> Hello list and trolls,
>
> I've just spend the morning debugging the weirdest bug, and I finally
> tracked it down to what it says in the title: when calling
> QObject::sender() inside a slot that was called by a signal, the
> receiver QObject has to "live" inside the same QThread as the emitter of
> the signal, otherwise the value of sender() is always NULL.
>
> I fully understand that using Qt::DirectConnection between objects that
> live in different threads is a bad idea, but all I need is
> sender()->objectName(), so that seems safe, especially as I have the
> certainty that sender() won't have been deleted in the mean time.
>
> And anyway, I'd very much like to be able to shoot myself in the foot if
> I feel like it :)
Well that use case is simply not supported by Qt. You need to use queued 
connections or blocking queued connections. 

If you are worried about lifetimes of you emitting objects then use some other 
method to ensure they survive. As an example you could emit a signal that 
takes a QSharedPointer as an argument where the shared pointer points at your 
emitting object. As long as at least one QSharedPointer points at your object, 
it will not be deleted.

A blocking queued connection will also work if you can live with the execution 
of your emitting thread pausing whilst the main thread services the request.

HTH,

Sean




More information about the Qt-interest-old mailing list