QVariant is cast to base type

I have a class like this:

class QObjectDerived : public QObject
{
    Q_OBJECT
    // ...
};
Q_DECLARE_METATYPE(QObjectDerived*)

      

When this class was stored in a QVariant, this behavior occurs

  QObjectDerived *object = new QObjectDerived(this);
  QVariant variant = QVariant::fromValue(object);
  qDebug() << variant;                          // prints QVariant(QObjectDerived*, )
  qDebug() << variant.value<QObject*>();        // prints QObject(0x0)
  qDebug() << variant.value<QObjectDerived*>(); // QObjectDerived(0x8c491c8)

  variant = QVariant::fromValue(static_cast<QObject*>(object));
  qDebug() << variant;                          // prints QVariant(QObject*, QObjectDerived(0x8c491c8) )
  qDebug() << variant.value<QObject*>();        // prints QObjectDerived(0x8c491c8)
  qDebug() << variant.value<QObjectDerived*>(); // QObject(0x0)

      

Is there a way to store it in a QVariant and get it as QObject * and QObjectDerived *?

+3


source to share


2 answers


Only by writing

QObject *value = variant.value<QObjectDerived*>();

      



You might be partially specializing qvariant_cast

for your type, but this is an undocumented supported use case and I wouldn't want to rely on it.

+1


source


qvariant.h (Qt 4.8.6):

template<typename T>
inline T value() const
{ return qvariant_cast<T>(*this); }

      

...



template<typename T> inline T qvariant_cast(const QVariant &v)
{
    const int vid = qMetaTypeId<T>(static_cast<T *>(0));
    if (vid == v.userType())
        return *reinterpret_cast<const T *>(v.constData());
    if (vid < int(QMetaType::User)) {
        T t;
    if (qvariant_cast_helper(v, QVariant::Type(vid), &t))
        return t;
    }
    return T();
}

      

QObject *

is stored as a built-in type QMetaType::QObjectStar

, but QObjectDerived

is a user-defined type with an identifier defined by the Meta-type system. This means that you have to manually hand it over.

0


source







All Articles