[Qt-interest] How to discover if a custom type stored into a QVariant inherits the QObject class

Girish Ramakrishnan girish at forwardbias.in
Sat Mar 20 07:40:40 CET 2010


Flavio Castelli wrote:
> Is it possible to know at run-time if a custom type stored into a QVariant 
> instance inherits the QObject class?
> 

QVariant doesn't actually understand types, inheritance heirarchy,
typeinfo...

So,
    variant.setValue<Derived *>(derived);
    Base *b = variant.value<Base *>();

The above won't work as you expect. As far as QVariant (QMetaType
really) is concered, Base * and Derived * have nothing to do with each
other. Each type is assigned a unique type id and QVariant::value()
merely compares the id of the casting type (Base * above) with the id of
what is inside the variant (Derived * above). In above case, they don't
match, so it will return 0;

As to how to make it work the way you want, just store the value as
QObject * everywhere. Don't bother registering Derived * as a metatype. So,
    variant.setValue<QObject *>(derived);
    QObject *b = variant.value<QObject *>();
    Derived *d = qobject_cast<Derived *>(d);

You are _guaranteed_ that whatever comes out above is a QObject, so a
qobject_cast later (to your Derived *) on the return value will never
crash. Non-QObject * types will always return in 0 returned.

You can also use the above trick for your custom class heirarchy which
is not based on QObject. Register the Base *. Store everything in
QVariant as Base *. Get values from QVariant as Base * and then use
dynamic_cast to get a derived pointer.

Girish



More information about the Qt-interest-old mailing list