[Qt-interest] How to discover if a custom type stored into a QVariant inherits the QObject class
K. Frank
kfrank29.c at gmail.com
Thu Mar 18 20:59:28 CET 2010
Flavio -
On Thu, Mar 18, 2010 at 1:33 PM, Flavio Castelli <flavio at castelli.name> wrote:
> Is it possible to know at run-time if a custom type stored into a QVariant
> instance inherits the QObject class?
Yes, you can use the standard run-time type information facility of C++
(assuming you haven't turned it off somehow).
> In the following example Person is a child of QObject:
>
> Person* p = new Person();
>
> QVariant v;
> v.setValue(p);
get pointer-to-Person out of the QVariant:
Person *pp = v.value<Person *>();
see if it's a pointer-to-QObject:
QObject *pq = dynamic_cast<QObject *>(pp);
dynamic_cast returns null if *pp doesn't inherit QObject:
if (pq) {
// Person is derived from QObject
}
else {
// Person is not derived from QObject
}
> qDebug() << v.canConvert<QObject*>(); // returns false
I don't know enough about QVariant's to know why canConvert for pointer
types isn't effectively the same as dynamic_cast, but I tried it out, and
it isn't.
> qDebug() << v.typeName(); // return Person*
> qDebug() << QVariant::nameToType(v.typeName()); //return QVariant::UserType
> delete p;
I don't know if there is some other way to use Qt's introspection system to
find out whether Person inherits QObject. (You would think there would be,
since, after all, that's what introspection is for.) Perhaps a Qt-meta-type
guru could shed some more light on this.
> Thanks in advance
> Flavio
K. Frank
More information about the Qt-interest-old
mailing list