[Qt-interest] qobject_cast Vs dynamic_cast

Sean Harmer sean.harmer at maps-technology.com
Thu Oct 21 09:34:50 CEST 2010


Hi,

On Thursday 21 October 2010 08:05:52 程梁 wrote:
> In my opinion, the best way to understand the implementation signals and
> slots is to read source code. You can check the marco SIGNALS and SLOTS.
> The SIGNALS makes function name to a string. I found Qt maintains a
> SIGNAL-SLOT map. In fact, when Qt found an emit keyword, it will change it
> to the slot function.

I do not think that this is correct. I think that the emit keyword actually 
expands to nothing. It is the signal function call which then goes into the 
signal/slot machinery generated by the moc. Eventually you'll end up in 
MyClass::qt_metacall() which contains a switch statement which will call the 
appropriate slot or signal (if any connections have been made) for you. 

This function and others are generated by the moc at compile time for you. 
Look for generated files with names in the format moc_myclass.cpp to see what 
gets generated. Near the top of the moc-generated files you'll see the 
structure used by the meta-object system to identify and map 
signals/slots/properties.

Best way to see it in action is to build a debug build of Qt and set a break 
point on a signal emission and use the debugger to step into the signal 
function call. This is easiest with direct connections as queued connections 
make use of the event loop for delayed processing.

> 2010/10/21 Sarvesh Saran <Sarvesh.Saran at synopsys.com>
> 
> >  Hi All,
> > 
> > I am trying to understand the differences between the qobject_cast  and
> > dynamic_cast and the advantages offered by qobject_cast.
> > 
> > 
> > 
> > According to QT documentation:
> > 
> > 
> > 
> > The qobject_cast() function behaves similarly to the standard C++
> > dynamic_cast(), with the advantages that it doesn't require RTTI support
> > and *it works across dynamic library boundaries*.
> > 
> > 
> > 
> > Can someone explain the meaning of the underlined words “it works across
> > dynamic library boundaries” ?

As it says, qobject_cast will work correctly if you try to cast an object from 
one library within another library (or application) whereas dynamic_cast may 
have trouble with this. Best to use qobject_cast if your objects are derived 
from QObject.

Cheers,

Sean




More information about the Qt-interest-old mailing list