[Qt-interest] qobject_cast<> questions

John McClurkin jwm at nei.nih.gov
Sat May 30 16:30:09 CEST 2009


Thiago Macieira wrote:
> Ross Bencina wrote:
>> Hi everyone
>>
>> Does anyone know exactly when qobject_cast is needed and why (ie where
>> dynamic_cast will crash)?
> 
> dynamic_cast should never crash. But it may fail to work if you are trying 
> to cast across DLL boundaries, depending on how the class was declared. 
> It's a problem caused by the platform ABI's deviating from the C++ 
> standard mandated behaviour: it's the case on Windows as well as on 
> platforms with hidden visibility.
> 
>> Is it only when using dynamically loaded
>> plugins, or can it happen with any use of Qt as a shared library such
>> as using the standard Qt DLLs and Frameworks from Qt Software (i'm on
>> Win32 and OSX)?
> 
> See above. If you're using Windows, you should know how that platform's 
> ABI breaks the C++ standard. I don't have all the details either: I'm 
> afraid you'll have to learn by experience.
> 
>> Also, can I rely on qobject_cast<> to work with null pointers? (ie to
>> return null if it is passed null?)
> 
> The source code for Qt is available and writing a test for that is a 
> couple of seconds.
> 
I use qobject_cast whenever I cast  an object derived from QWidget to 
another type of object derived from QWidget. Qobject_cast will return 
null if the cast cannot be made. For example, in looping through the 
subwindows of a QMdiArea, I use qobject_cast to cast the internal widget 
to one of the types that were added to the QMidArea. When I am looking 
for an object derived from QMainWindow that was added to the QMdiArea, 
and a particular internal widget was derived from a QDialog, the cast 
will return NULL, and I continue the loop until I get to an internal 
that can be cast to a widget derived from a QMainWindow.



More information about the Qt-interest-old mailing list