原创文章,转载请注明出处,谢谢!
作者:清林,博客名:飞空静渡
QVariant可以表示QT中的大部分类型,它和pascal中的variant类型或c中的void类型有点相似,不过它的使用和c中的union类似,其实现也是用union,在qvariant.h头文件中,我们可以看到这样定义:
view plaincopy to clipboardprint?
class Q_CORE_EXPORT QVariant
{
public:
enum Type {
Invalid = 0,
Bool = 1,
Int = 2,
UInt = 3,
LongLong = 4,
ULongLong = 5,
......
UserType = 127,
#ifdef QT3_SUPPORT
IconSet = Icon,
CString = ByteArray,
PointArray = Polygon,
#endif
LastType = 0xffffffff // need this so that gcc >= 3.4 allocates 32 bits for Type
};
inline QVariant();
...............
}
class Q_CORE_EXPORT QVariant
{
public:
enum Type {
Invalid = 0,
Bool = 1,
Int = 2,
UInt = 3,
LongLong = 4,
ULongLong = 5,
......
UserType = 127,
#ifdef QT3_SUPPORT
IconSet = Icon,
CString = ByteArray,
PointArray = Polygon,
#endif
LastType = 0xffffffff // need this so that gcc >= 3.4 allocates 32 bits for Type
};
inline QVariant();
...............
}
我们可以用type()成员函数来返回它的类型:Type QVariant::type () const 。
为了取得它的值,我们可以用类似的toT()这样的函数来取得,如toInt()、toString()等。
基本的使用如下:
view plaincopy to clipboardprint?
QDataStream out(...);
QVariant v(123); // The variant now contains an int
int x = v.toInt(); // x = 123
out << v; // Writes a type tag and an int to out
v = QVariant("hello"); // The variant now contains a QByteArray
v = QVariant(tr("hello")); // The variant now contains a QString
int y = v.toInt(); // y = 0 since v cannot be converted to an int
QString s = v.toString(); // s = tr("hello") (see QObject::tr())
out << v; // Writes a type tag and a QString to out
...
QDataStream in(...); // (opening the previously written stream)
in >> v; // Reads an Int variant
int z = v.toInt(); // z = 123
qDebug("Type is %s", // prints "Type is int"
v.typeName());
v = v.toInt() + 100; // The variant now hold the value 223
v = QVariant(QStringList());
QDataStream out(...);
QVariant v(123); // The variant