The QVariant class acts like a union for the most common Qt data types.
QVariant 类作用类似与绝大部分Qt数据类型。
Because C++ forbids unions from including types that have non-default constructors or destructors, most interesting Qt classes cannot be used in unions. Without QVariant, this would be a problem for QObject::property() and for database work, etc.
A QVariant object holds a single value of a single type() at a time. (Some type()s are multi-valued, for example a string list.) You can find out what type, T, the variant holds, convert it to a different type using convert(), get its value using one of the toT() functions (e.g., toSize()) and check whether the type can be converted to a particular type using canConvert().
因为C++禁止联合体包含非默认构造函数或析构函数的类型,所以大多数有趣的QT类不能用于联合。如果没有QVariant,这对QObject::property()和数据库工作来说都是一个问题
QVariant对象一次只保存一个类型()的单个值。(有些类型()是多值的,例如字符串列表。)您可以找出变量所包含的类型T,使用convert()将其转换为其他类型,使用toT()函数之一(例如toSize())获取其值,并使用canConvert()检查是否可以将该类型转换为特定类型。
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());