Qt下的QVariant类

September 12th, 2016 by JasonLe's Tech Leave a reply »

QVariant是一个数据类型类,存储不同类型的数据结构,一般情况下C++的class都不允许没有构造函数和析构函数存在。为了方便数据库对象存取,可以使用QVariant class。一个QVariant对象在一个时间内只保留一种类型的值。我们可以使用canConvert来查询是否能够转换当前的类型。转换类型一般以toT()命名。

QVariant可以保存很多Qt的数据类型,通过查看Document,可以知道发现支持很多Qt特定的数据类型,并且还有C++基本类型,如int、float等。QVariant还能保存很多集合类型,如QMap<QString, QVariant>, QStringList和QList<QVariant>等,因此QVariant完全满足现有编程需要。

今天在写代码过程中,尤其是读取数据库大量记录时,这个类足够好用。

struct s_field
{
      int type;
      QString fieldnum;
}
struct s_record
{
      QList<s_field> fieldlist;
      QString tableName;
}

struct s_recorddata
{
      QList<QVariant> datalist;
}
QList<s_recorddata> listdata;

通过这个数据结构我们可以把读到的数据放到listdata中,而每一个datalist都是一条记录,datalist中每一个的QVariant都是一个字段,我们不仅可以通过这个字段读取到数据,也可以判断具体的数据类型。

Type QVariant::type() const

Returns the storage type of the value stored in the variant. Although this function is declared as returning QVariant::Type, the return value should be interpreted as QMetaType::Type. In particular, QVariant::UserType is returned here only if the value is equal or greater than QMetaType::User.

Note that return values in the ranges QVariant::Char through QVariant::RegExp and QVariant::Font through QVariant::Transform correspond to the values in the ranges QMetaType::QChar through QMetaType::QRegExp and QMetaType::QFont through QMetaType::QQuaternion.

Pay particular attention when working with char and QChar variants. Note that there is no QVariant constructor specifically for type char, but there is one for QChar. For a variant of type QChar, this function returns QVariant::Char, which is the same as QMetaType::QChar, but for a variant of type char, this function returns QMetaType::Char, which is not the same as QVariant::Char.

Also note that the types void*, long, short, unsigned long, unsigned short, unsigned char, float, QObject*, and QWidget* are represented in QMetaType::Type but not in QVariant::Type, and they can be returned by this function. However, they are considered to be user defined types when tested against QVariant::Type.

To test whether an instance of QVariant contains a data type that is compatible with the data type you are interested in, use canConvert().

按照上面的数据结构和声明,只要listdata[i].datalist[j].type()就可以返回具体枚举类型,然后想返回具体值就是使用listdata[i].datalist[j].toInt() 或者其他的toxxx()即可。赋值的具体用法就是直接赋值即可。QVariant var; var = datatime …. var = 5 … var = 5.0 …

 

参考:

http://doc.qt.io/qt-4.8/qvariant.html#QVariant-2