QVariant 转换为基本类型

QVariant cast to base type

我有一些 class 这样的:

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

当此 class 存储到 QVariant 时,会发生这种行为

  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)

有没有办法将它存储在 QVariant 中并能够将其作为 QObject* 和 QObjectDerived* 获取?

只有写

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

可能 可以针对您的类型部分特化 qvariant_cast,但这不是一个有文档支持的用例,我不愿意依赖它.

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 *存储为内置的QMetaType::QObjectStar类型,QObjectDerived为用户自定义类型,id为Meta-type系统定义。这意味着,您必须手动投射它。