我正在编写测试代码,该代码将自动遍历所有Q_PROPERTY的小部件,并且某些属性正在使用通过qRegisterMetaType注册的类型。如果我想将它们读/写到QVariant中,则在将它们存储到变量中时需要使用QVariant::UserType。到现在为止还挺好。

但是,当我想测试这些属性的读写时,我还需要知道它们的类型。对于已经是标准qt类型的东西,我可以通过QVariant::type()做到这一点,但是由于我有很多用户类型,这将如何实现?

从QVariant的api中,我发现了这一点:
bool QVariant::canConvert ( Type t ) const
但是我有点怀疑在枚举的情况下这是否会导致错误的类型?

那么,验证QVariant中存储哪种类型的用户类型的万无一失的方法是什么?

最佳答案

对于用户定义的类型,存在QVariant::userType()。它的工作方式类似于QVariant::type(),但返回用户定义类型的类型ID整数,而QVariant::type()始终返回QVariant::UserType。

还有QVariant::typeName(),它以字符串形式返回类型的名称。

编辑 :

这可能取决于您如何设置QVariant。不建议直接使用QVariant::QVariant(int type, const void * copy)

说我有以下三种类型:

class MyFirstType
{
    public:
        MyFirstType();
        MyFirstType(const MyFirstType &other);
        ~MyFirstType();

        MyFirstType(const QString &content);

        QString content() const;

    private:
        QString m_content;
};
Q_DECLARE_METATYPE(MyFirstType);

第三个没有Q_DECLARE_METATYPE

我将它们存储在QVariant中:
 QString content = "Test";

 MyFirstType first(content);

 MySecondType second(content);

 MyThirdType third(content);

 QVariant firstVariant;
 firstVariant.setValue(first);

 QVariant secondVariant = QVariant::fromValue(second);

 int myType = qRegisterMetaType<MyThirdType>("MyThirdType");

 QVariant thirdVariant(myType, &third); // Here the type isn't checked against the data passed

 qDebug() << "typeName for first :" << firstVariant.typeName();
 qDebug() << "UserType :" << firstVariant.userType();
 qDebug() << "Type : " << firstVariant.type();

 [...]

我得到:
typeName for first : MyFirstType
UserType : 256
Type :  QVariant::UserType

typeName for second : MySecondType
UserType : 257
Type :  QVariant::UserType

typeName for third : MyThirdType
UserType : 258
Type :  QVariant::UserType

关于qt - 如何验证QVariant::UserType类型的QVariant是预期类型?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3193275/

10-12 05:15