Home · All Classes · Modules

QVariant Class Reference
[QtCore module]

The QVariant class acts like a union for the most common Qt data types. More...

Types

Methods

Static Methods

Special Methods


Detailed Description

Any Python object may be used whenever a QVariant is expected. None will be interpreted as an invalid QVariant.

The QVariant class acts like a union for the most common Qt data types.

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().

The methods named toT() (e.g., toInt(), toString()) are const. If you ask for the stored type, they return a copy of the stored object. If you ask for a type that can be generated from the stored type, toT() copies and converts and leaves the object itself unchanged. If you ask for a type that cannot be generated from the stored type, the result depends on the type; see the function documentation for details.

Here is some example code to demonstrate the use of QVariant:

 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());

You can even store QList<QVariant> and QMap<QString, QVariant> values in a variant, so you can easily construct arbitrarily complex data structures of arbitrary types. This is very powerful and versatile, but may prove less memory and speed efficient than storing specific types in standard data structures.

QVariant also supports the notion of null values, where you can have a defined type with no value set. However, note that QVariant types can only be cast when they have had a value set.

 QVariant x, y(QString()), z(QString(""));
 x.convert(QVariant.Int);
 // x.isNull() == true
 // y.isNull() == true, z.isNull() == false

QVariant can be extended to support other types than those mentioned in the Type enum. See the QMetaType documentation for details.

A Note on GUI Types

Because QVariant is part of the QtCore library, it cannot provide conversion functions to data types defined in QtGui, such as QColor, QImage, and QPixmap. In other words, there is no toColor() function. Instead, you can use the QVariant.value() or the qVariantValue() template function. For example:

 QVariant variant;
 ...
 QColor color = variant.value<QColor>();

The inverse conversion (e.g., from QColor to QVariant) is automatic for all data types supported by QVariant, including GUI-related types:

 QColor color = palette().background().color();
 QVariant variant = color;

Using canConvert() and convert() Consecutively

When using canConvert() and convert() consecutively, it is possible for canConvert() to return true, but convert() to return false. This is typically because canConvert() only reports the general ability of QVariant to convert between types given suitable data; it is still possible to supply data which cannot actually be converted.

For example, canConvert() would return true when called on a variant containing a string because, in principle, QVariant is able to convert strings of numbers to integers. However, if the string contains non-numeric characters, it cannot be converted to an integer, and any attempt to convert it will fail. Hence, it is important to have both functions return true for a successful conversion.

See also QMetaType.


Type Documentation

QVariant.Type

This enum type defines the types of variable that a QVariant can contain.

ConstantValueDescription
QVariant.Invalid0no type
QVariant.BitArray13a QBitArray
QVariant.Bitmap73a QBitmap
QVariant.Bool1a bool
QVariant.Brush66a QBrush
QVariant.ByteArray12a QByteArray
QVariant.Char7a QChar
QVariant.Color67a QColor
QVariant.Cursor74a QCursor
QVariant.Date14a QDate
QVariant.DateTime16a QDateTime
QVariant.Double6a double
QVariant.Font64a QFont
QVariant.Hash28a QVariantHash
QVariant.Icon69a QIcon
QVariant.Image70a QImage
QVariant.Int2an int
QVariant.KeySequence76a QKeySequence
QVariant.Line23a QLine
QVariant.LineF24a QLineF
QVariant.List9a QVariantList
QVariant.Locale18a QLocale
QVariant.LongLong4a qlonglong
QVariant.Map8a QVariantMap
QVariant.Matrix80a QMatrix(obsolete)
QVariant.Transform81a QTransform
QVariant.Matrix4x482a QMatrix4x4
QVariant.Palette68a QPalette
QVariant.Pen77a QPen
QVariant.Pixmap65a QPixmap
QVariant.Point25a QPoint
QVariant.PointArrayPolygona QPointArray
QVariant.PointF26a QPointF
QVariant.Polygon71a QPolygon
QVariant.Quaternion86a QQuaternion
QVariant.Rect19a QRect
QVariant.RectF20a QRectF
QVariant.RegExp27a QRegExp
QVariant.Region72a QRegion
QVariant.Size21a QSize
QVariant.SizeF22a QSizeF
QVariant.SizePolicy75a QSizePolicy
QVariant.String10a QString
QVariant.StringList11a QStringList
QVariant.TextFormat79a QTextFormat
QVariant.TextLength78a QTextLength
QVariant.Time15a QTime
QVariant.UInt3a uint
QVariant.ULongLong5a qulonglong
QVariant.Url17a QUrl
QVariant.Vector2D83a QVector2D
QVariant.Vector3D84a QVector3D
QVariant.Vector4D85a QVector4D
QVariant.UserType127Base value for user-defined types.


Method Documentation

QVariant.__init__ (self)

Constructs an invalid variant.

QVariant.__init__ (self, Type)

Constructs a null variant of type type.

QVariant.__init__ (self, int, sip.voidptr)

Constructs variant of type typeOrUserType, and initializes with copy if copy is not 0.

Note that you have to pass the address of the variable you want stored.

Usually, you never have to use this constructor, use qVariantFromValue() instead to construct variants from the pointer types represented by QMetaType.VoidStar, QMetaType.QObjectStar and QMetaType.QWidgetStar.

See also qVariantFromValue() and Type.

QVariant.__init__ (self, QVariant)

QVariant.__init__ (self, object)

Constructs a copy of the variant, p, passed as the argument to this constructor.

bool QVariant.canConvert (self, Type)

Returns true if the variant's type can be cast to the requested type, t. Such casting is done automatically when calling the toInt(), toBool(), ... methods.

The following casts are done automatically:

TypeAutomatically Cast To
BoolChar, Double, Int, LongLong, String, UInt, ULongLong
ByteArrayDouble, Int, LongLong, String, UInt, ULongLong
CharBool, Int, UInt, LongLong, ULongLong
ColorString
DateDateTime, String
DateTimeDate, String, Time
DoubleBool, Int, LongLong, String, UInt, ULongLong
FontString
IntBool, Char, Double, LongLong, String, UInt, ULongLong
KeySequenceInt, String
ListStringList (if the list's items can be converted to strings)
LongLongBool, ByteArray, Char, Double, Int, String, UInt, ULongLong
PointPointF
RectRectF
StringBool, ByteArray, Char, Color, Date, DateTime, Double, Font, Int, KeySequence, LongLong, StringList, Time, UInt, ULongLong
StringListList, String (if the list contains exactly one item)
TimeString
UIntBool, Char, Double, Int, LongLong, String, ULongLong
ULongLongBool, Char, Double, Int, LongLong, String, UInt

See also convert().

QVariant.clear (self)

Convert this variant to type Invalid and free up any resources used.

bool QVariant.convert (self, Type)

Casts the variant to the requested type, t. If the cast cannot be done, the variant is cleared. Returns true if the current type of the variant was successfully cast; otherwise returns false.

Warning: For historical reasons, converting a null QVariant results in a null value of the desired type (e.g., an empty string for QString) and a result of false.

See also canConvert() and clear().

sip.voidptr QVariant.data (self)

QVariant.detach (self)

QVariant QVariant.fromList (list-of-QVariant list)

QVariant QVariant.fromMap (dict-of-QString-QVariant map)

bool QVariant.isDetached (self)

bool QVariant.isNull (self)

Returns true if this is a NULL variant, false otherwise.

bool QVariant.isValid (self)

Returns true if the storage type of this variant is not QVariant.Invalid; otherwise returns false.

QVariant.load (self, QDataStream)

Type QVariant.nameToType (str)

Converts the string representation of the storage type given in name, to its enum representation.

If the string representation cannot be converted to any enum representation, the variant is set to Invalid.

QVariant.save (self, QDataStream)

QBitArray QVariant.toBitArray (self)

Returns the variant as a QBitArray if the variant has type() BitArray; otherwise returns an empty bit array.

See also canConvert() and convert().

bool QVariant.toBool (self)

Returns the variant as a bool if the variant has type() Bool.

Returns true if the variant has type() Bool, Char, Double, Int, LongLong, UInt, or ULongLong and the value is non-zero, or if the variant has type String or ByteArray and its lower-case content is not empty, "0" or "false"; otherwise returns false.

See also canConvert() and convert().

QByteArray QVariant.toByteArray (self)

Returns the variant as a QByteArray if the variant has type() ByteArray or String (converted using QString.fromAscii()); otherwise returns an empty byte array.

See also canConvert() and convert().

QChar QVariant.toChar (self)

Returns the variant as a QChar if the variant has type() Char, Int, or UInt; otherwise returns an invalid QChar.

See also canConvert() and convert().

QDate QVariant.toDate (self)

Returns the variant as a QDate if the variant has type() Date, DateTime, or String; otherwise returns an invalid date.

If the type() is String, an invalid date will be returned if the string cannot be parsed as a Qt.ISODate format date.

See also canConvert() and convert().

QDateTime QVariant.toDateTime (self)

Returns the variant as a QDateTime if the variant has type() DateTime, Date, or String; otherwise returns an invalid date/time.

If the type() is String, an invalid date/time will be returned if the string cannot be parsed as a Qt.ISODate format date/time.

See also canConvert() and convert().

(float, bool ok) QVariant.toDouble (self)

Returns the variant as a double if the variant has type() Double, QMetaType.Float, Bool, ByteArray, Int, LongLong, String, UInt, or ULongLong; otherwise returns 0.0.

If ok is non-null: *ok is set to true if the value could be converted to a double; otherwise *ok is set to false.

See also canConvert() and convert().

(float, bool ok) QVariant.toFloat (self)

Returns the variant as a float if the variant has type() Double, QMetaType.Float, Bool, ByteArray, Int, LongLong, String, UInt, or ULongLong; otherwise returns 0.0.

If ok is non-null: *ok is set to true if the value could be converted to a double; otherwise *ok is set to false.

This function was introduced in Qt 4.6.

See also canConvert() and convert().

dict-of-QString-QVariant QVariant.toHash (self)

Returns the variant as a QHash<QString, QVariant> if the variant has type() Hash; otherwise returns an empty map.

See also canConvert() and convert().

(int, bool ok) QVariant.toInt (self)

Returns the variant as an int if the variant has type() Int, Bool, ByteArray, Char, Double, LongLong, String, UInt, or ULongLong; otherwise returns 0.

If ok is non-null: *ok is set to true if the value could be converted to an int; otherwise *ok is set to false.

Warning: If the value is convertible to a LongLong but is too large to be represented in an int, the resulting arithmetic overflow will not be reflected in ok. A simple workaround is to use QString.toInt(). Fixing this bug has been postponed to Qt 5 in order to avoid breaking existing code.

See also canConvert() and convert().

QLine QVariant.toLine (self)

Returns the variant as a QLine if the variant has type() Line; otherwise returns an invalid QLine.

See also canConvert() and convert().

QLineF QVariant.toLineF (self)

Returns the variant as a QLineF if the variant has type() LineF; otherwise returns an invalid QLineF.

See also canConvert() and convert().

list-of-QVariant QVariant.toList (self)

Returns the variant as a QVariantList if the variant has type() List or StringList; otherwise returns an empty list.

See also canConvert() and convert().

QLocale QVariant.toLocale (self)

Returns the variant as a QLocale if the variant has type() Locale; otherwise returns an invalid QLocale.

See also canConvert() and convert().

(int, bool ok) QVariant.toLongLong (self)

Returns the variant as a long long int if the variant has type() LongLong, Bool, ByteArray, Char, Double, Int, String, UInt, or ULongLong; otherwise returns 0.

If ok is non-null: *ok is set to true if the value could be converted to an int; otherwise *ok is set to false.

See also canConvert() and convert().

dict-of-QString-QVariant QVariant.toMap (self)

Returns the variant as a QMap<QString, QVariant> if the variant has type() Map; otherwise returns an empty map.

See also canConvert() and convert().

QPoint QVariant.toPoint (self)

Returns the variant as a QPoint if the variant has type() Point or PointF; otherwise returns a null QPoint.

See also canConvert() and convert().

QPointF QVariant.toPointF (self)

Returns the variant as a QPointF if the variant has type() Point or PointF; otherwise returns a null QPointF.

See also canConvert() and convert().

object QVariant.toPyObject (self)

(float, bool ok) QVariant.toReal (self)

Returns the variant as a qreal if the variant has type() Double, QMetaType.Float, Bool, ByteArray, Int, LongLong, String, UInt, or ULongLong; otherwise returns 0.0.

If ok is non-null: *ok is set to true if the value could be converted to a double; otherwise *ok is set to false.

This function was introduced in Qt 4.6.

See also canConvert() and convert().

QRect QVariant.toRect (self)

Returns the variant as a QRect if the variant has type() Rect; otherwise returns an invalid QRect.

See also canConvert() and convert().

QRectF QVariant.toRectF (self)

Returns the variant as a QRectF if the variant has type() Rect or RectF; otherwise returns an invalid QRectF.

See also canConvert() and convert().

QRegExp QVariant.toRegExp (self)

Returns the variant as a QRegExp if the variant has type() RegExp; otherwise returns an empty QRegExp.

This function was introduced in Qt 4.1.

See also canConvert() and convert().

QSize QVariant.toSize (self)

Returns the variant as a QSize if the variant has type() Size; otherwise returns an invalid QSize.

See also canConvert() and convert().

QSizeF QVariant.toSizeF (self)

Returns the variant as a QSizeF if the variant has type() SizeF; otherwise returns an invalid QSizeF.

See also canConvert() and convert().

QString QVariant.toString (self)

Returns the variant as a QString if the variant has type() String, Bool, ByteArray, Char, Date, DateTime, Double, Int, LongLong, StringList, Time, UInt, or ULongLong; otherwise returns an empty string.

See also canConvert() and convert().

QStringList QVariant.toStringList (self)

Returns the variant as a QStringList if the variant has type() StringList, String, or List of a type that can be converted to QString; otherwise returns an empty list.

See also canConvert() and convert().

QTime QVariant.toTime (self)

Returns the variant as a QTime if the variant has type() Time, DateTime, or String; otherwise returns an invalid time.

If the type() is String, an invalid time will be returned if the string cannot be parsed as a Qt.ISODate format time.

See also canConvert() and convert().

(int, bool ok) QVariant.toUInt (self)

Returns the variant as an unsigned int if the variant has type() UInt, Bool, ByteArray, Char, Double, Int, LongLong, String, or ULongLong; otherwise returns 0.

If ok is non-null: *ok is set to true if the value could be converted to an unsigned int; otherwise *ok is set to false.

Warning: If the value is convertible to a ULongLong but is too large to be represented in an unsigned int, the resulting arithmetic overflow will not be reflected in ok. A simple workaround is to use QString.toUInt(). Fixing this bug has been postponed to Qt 5 in order to avoid breaking existing code.

See also canConvert() and convert().

(int, bool ok) QVariant.toULongLong (self)

Returns the variant as as an unsigned long long int if the variant has type() ULongLong, Bool, ByteArray, Char, Double, Int, LongLong, String, or UInt; otherwise returns 0.

If ok is non-null: *ok is set to true if the value could be converted to an int; otherwise *ok is set to false.

See also canConvert() and convert().

QUrl QVariant.toUrl (self)

Returns the variant as a QUrl if the variant has type() Url; otherwise returns an invalid QUrl.

See also canConvert() and convert().

Type QVariant.type (self)

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().

str QVariant.typeName (self)

Returns the name of the type stored in the variant. The returned strings describe the C++ datatype used to store the data: for example, "QFont", "QString", or "QVariantList". An Invalid variant returns 0.

str QVariant.typeToName (Type)

Converts the enum representation of the storage type, typ, to its string representation.

Returns a null pointer if the type is QVariant.Invalid or doesn't exist.

int QVariant.userType (self)

Returns the storage type of the value stored in the variant. For non-user types, this is the same as type().

See also type().

bool QVariant.__eq__ (self, QVariant)

bool QVariant.__ne__ (self, QVariant)


PyQt 4.7.3 for X11Copyright © Riverbank Computing Ltd and Nokia 2010Qt 4.6.2