QVariant可以表示QT中的大部分类型,它和pascal中的variant类型或c中的void类型有点相似,
不过它的使用和c中的union类似,其实现也是用union
,在qvariant.h头文件中,我们可以看到这样定义:
- 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()等。
基本的使用如下:
- 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());
QViriant支持空值的使用,你可以定义一个空的QViriant,并在后面才给它赋值。
- QVariant x, y(QString()), z(QString(""));
- x.convert(QVariant::Int);
- // x.isNull() == true
- // y.isNull() == true, z.isNull() == false
- // y.isEmpty() == true, z.isEmpty() == true
QVariant是定义在QtCore库中的,前面说的qvariant.h就在QtCore目录下,因此它不提供类似于toInt()、toString()这样的函数去转化QtGui中的类型,如QColor、QImage和QPixmap等。但你可以使用QVariant::value()或者qVariantValue()模板函数转化。
- QVariant variant;
- ...
- QColor color = variant.value<QColor>();
相反的赋值就可以这样:
- QColor color = palette().background().color();
- QVariant variant = color;
你可以使用canConvert()确定是否可以转化。