QVariant转换为基类型

时间:2015-05-26 07:54:53

标签: c++ qt4

我有这样的课程:

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

当此类存储到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 *?

2 个答案:

答案 0 :(得分:1)

仅写作

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

可能可以为您的类型部分专门化qvariant_cast,但这不是文档支持的用例,而且我不愿意依赖它

答案 1 :(得分:0)

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类型系统定义。这意味着,您必须手动投射。