代码之家  ›  专栏  ›  技术社区  ›  rasjani

如何验证QVariant::UserType类型的QVariant是否为预期类型?

  •  7
  • rasjani  · 技术社区  · 16 年前

    我正在编写测试代码,它将自动遍历小部件的所有Q\u属性,一些属性使用通过qRegisterMetaType注册的类型。如果我想把它们读写到QVariant中,我需要在将它们存储到variant中时使用QVariant::UserType。到现在为止,一直都还不错。

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

    从QVariant的api中,我发现了:

    bool QVariant::canConvert ( Type t ) const

    那么,验证QVariant中存储的用户类型的简单方法是什么呢?

    1 回复  |  直到 16 年前
        1
  •  14
  •   cantSleepNow    10 年前

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

    还有 QVariant::typeName()

    编辑:

    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\u的声明\u元类型

    我把它们储存在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 
    
    推荐文章