Viadeo Twitter Google Bookmarks ! Facebook Digg del.icio.us MySpace Yahoo MyWeb Blinklist Netvouz Reddit Simpy StumbleUpon Bookmarks Windows Live Favorites 
Logo Documentation Qt ·  Page d'accueil  ·  Toutes les classes  ·  Classes principales  ·  Annotées  ·  Classes groupées  ·  Modules  ·  Fonctions  · 

QVariant Class Reference
[QtCore module]

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

#include <QVariant>

Public Types

  • enum Type { Invalid, BitArray, Bitmap, Bool, ..., UserType }

Public Functions

Static Public Members

Related Non-Members


Detailed Description

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 have a defined type with no value set.

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

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 such as QColor, QImage, and QPixmap, which are part of QtGui. 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;

See also QMetaType.


Member Type Documentation

enum 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::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::Palette68a QPalette
QVariant::Pen77a QPen
QVariant::Pixmap65a QPixmap
QVariant::Point25a QPoint
QVariant::PointArrayPolygona QPointArray
QVariant::PointF26a QPointF
QVariant::Polygon71a QPolygon
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::UserType127Base value for user-defined types.


Member Function Documentation

QVariant::QVariant ()

Constructs an invalid variant.

QVariant::QVariant ( Type type )

Constructs a null variant of type type.

QVariant::QVariant ( int typeOrUserType, const void * copy )

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::QVariant ( const QVariant & p )

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

QVariant::QVariant ( QDataStream & s )

Reads the variant from the data stream, s.

QVariant::QVariant ( int val )

Constructs a new variant with an integer value, val.

QVariant::QVariant ( uint val )

Constructs a new variant with an unsigned integer value, val.

QVariant::QVariant ( qlonglong val )

Constructs a new variant with a long long integer value, val.

QVariant::QVariant ( qulonglong val )

Constructs a new variant with an unsigned long long integer value, val.

QVariant::QVariant ( bool val )

Constructs a new variant with a boolean value, val. The integer argument is a dummy, necessary for compatibility with some compilers.

QVariant::QVariant ( double val )

Constructs a new variant with a floating point value, val.

QVariant::QVariant ( const char * val )

Constructs a new variant with a string value of val. The variant creates a deep copy of val, using the encoding set by QTextCodec::setCodecForCStrings().

You can disable this operator by defining QT_NO_CAST_FROM_ASCII when you compile your applications.

See also QTextCodec::setCodecForCStrings().

QVariant::QVariant ( const QByteArray & val )

Constructs a new variant with a bytearray value, val.

QVariant::QVariant ( const QBitArray & val )

Constructs a new variant with a bitarray value, val.

QVariant::QVariant ( const QString & val )

Constructs a new variant with a string value, val.

QVariant::QVariant ( const QLatin1String & val )

Constructs a new variant with a string value, val.

QVariant::QVariant ( const QStringList & val )

Constructs a new variant with a string list value, val.

QVariant::QVariant ( const QChar & c )

Constructs a new variant with a char value, c.

QVariant::QVariant ( const QDate & val )

Constructs a new variant with a date value, val.

QVariant::QVariant ( const QTime & val )

Constructs a new variant with a time value, val.

QVariant::QVariant ( const QDateTime & val )

Constructs a new variant with a date/time value, val.

QVariant::QVariant ( const QList<QVariant> & val )

Constructs a new variant with a list value, val.

QVariant::QVariant ( const QMap<QString, QVariant> & val )

Constructs a new variant with a map of QVariants, val.

QVariant::QVariant ( const QSize & val )

Constructs a new variant with a size value of val.

QVariant::QVariant ( const QSizeF & val )

Constructs a new variant with a size value of val.

QVariant::QVariant ( const QPoint & val )

Constructs a new variant with a point value of val.

QVariant::QVariant ( const QPointF & val )

Constructs a new variant with a point value of val.

QVariant::QVariant ( const QLine & val )

Constructs a new variant with a line value of val.

QVariant::QVariant ( const QLineF & val )

Constructs a new variant with a line value of val.

QVariant::QVariant ( const QRect & val )

Constructs a new variant with a rect value of val.

QVariant::QVariant ( const QRectF & val )

Constructs a new variant with a rect value of val.

QVariant::QVariant ( const QUrl & val )

Constructs a new variant with a url value of val.

QVariant::QVariant ( const QLocale & l )

Constructs a new variant with a locale value, l.

QVariant::QVariant ( const QRegExp & regExp )

Constructs a new variant with the regexp value regExp.

QVariant::~QVariant ()

Destroys the QVariant and the contained object.

Note that subclasses that reimplement clear() should reimplement the destructor to call clear(). This destructor calls clear(), but because it is the destructor, QVariant::clear() is called rather than a subclass's clear().

bool QVariant::canConvert ( Type t ) const

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)
TimeDateTime, String
UIntBool, Char, Double, Int, LongLong, String, ULongLong
ULongLongBool, Char, Double, Int, LongLong, String, UInt

See also convert().

bool QVariant::canConvert () const

This is an overloaded member function, provided for convenience.

Returns true if the variant can be converted to the template type T, otherwise false.

Example:

    QVariant v = 42;

    v.canConvert<int>();              // returns true
    v.canConvert<QString>();          // returns true

    MyCustomStruct s;
    v.setValue(s);

    v.canConvert<int>();              // returns false
    v.canConvert<MyCustomStruct>();   // returns true

Warning: This function is not available with MSVC 6. Use qVariantCanConvert() instead if you need to support that version of the compiler.

See also convert().

void QVariant::clear ()

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

bool QVariant::convert ( Type t )

Casts the variant to the requested type. If the cast cannot be done, the variant is set to the default value of the requested type (e.g. an empty string if the requested type t is QVariant::String, an empty point array if the requested type t is QVariant::Polygon, etc). Returns true if the current type of the variant was successfully cast; otherwise returns false.

See also canConvert().

QVariant QVariant::fromValue ( const T & value )   [static]

Returns a QVariant containing a copy of value. Behaves exactly like setValue() otherwise.

Example:

    MyCustomStruct s;
    return QVariant::fromValue(s);

Warning: This function is not available with MSVC 6. Use qVariantFromValue() instead if you need to support that version of the compiler.

See also setValue() and value().

bool QVariant::isNull () const

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

bool QVariant::isValid () const

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

Type QVariant::nameToType ( const char * name )   [static]

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.

void QVariant::setValue ( const T & value )

Stores a copy of value. If T is a type that QVariant doesn't support, QMetaType is used to store the value. A compile error will occur if QMetaType doesn't handle the type.

Example:

    QVariant v;

    v.setValue(5);
    int i = v.toInt();         // i is now 5
    QString s = v.toString()   // s is now "5"

    MyCustomStruct c;
    v.setValue(c);

    ...

    MyCustomStruct c2 = v.value<MyCustomStruct>();

Warning: This function is not available with MSVC 6. Use qVariantSetValue() instead if you need to support that version of the compiler.

See also value(), fromValue(), and canConvert().

QBitArray QVariant::toBitArray () const

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

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 and its lower-case content is not empty, "0" or "false"; otherwise returns false.

See also canConvert() and convert().

QByteArray QVariant::toByteArray () const

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

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

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

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

double QVariant::toDouble ( bool * ok = 0 ) const

Returns the variant as a double if the variant has type() Double, 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().

int QVariant::toInt ( bool * ok = 0 ) const

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.

See also canConvert() and convert().

QLine QVariant::toLine () const

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

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

See also canConvert() and convert().

QList<QVariant> QVariant::toList () const

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

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

See also canConvert() and convert().

qlonglong QVariant::toLongLong ( bool * ok = 0 ) const

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

QMap<QString, QVariant> QVariant::toMap () const

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

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

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

See also canConvert() and convert().

QRect QVariant::toRect () const

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

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

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

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

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

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

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

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

uint QVariant::toUInt ( bool * ok = 0 ) const

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.

See also canConvert() and convert().

qulonglong QVariant::toULongLong ( bool * ok = 0 ) const

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

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

Returns the storage type of the value stored in the variant. Usually it's best to test with canConvert() whether the variant can deliver the data type you are interested in.

const char * QVariant::typeName () const

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.

const char * QVariant::typeToName ( Type typ )   [static]

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

int QVariant::userType () const

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

See also type().

T QVariant::value () const

Returns the stored value converted to the template type T. Call canConvert() to find out whether a type can be converted. If the value cannot be converted, default-constructed value will be returned.

If the type T is supported by QVariant, this function behaves exactly as toString(), toInt() etc.

Example:

    QVariant v;

    MyCustomStruct c;
    if (v.canConvert<MyCustomStruct>())
        c = v.value<MyCustomStruct>(v);

    v = 7;
    int i = v.value<int>();                        // same as v.toInt()
    QString s = v.value<QString>();                // same as v.toString(), s is now "7"
    MyCustomStruct c2 = v.value<MyCustomStruct>(); // conversion failed, c2 is empty

Warning: This function is not available with MSVC 6. Use qVariantValue() or qvariant_cast() instead if you need to support that version of the compiler.

See also setValue(), fromValue(), and canConvert().

bool QVariant::operator!= ( const QVariant & v ) const

Compares this QVariant with v and returns true if they are not equal; otherwise returns false.

Warning: This function doesn't support custom types registered with qRegisterMetaType().

QVariant & QVariant::operator= ( const QVariant & variant )

Assigns the value of the variant variant to this variant.

bool QVariant::operator== ( const QVariant & v ) const

Compares this QVariant with v and returns true if they are equal; otherwise returns false.

Warning: This function doesn't support custom types registered with qRegisterMetaType().


Related Non-Members

typedef QVariantList

Synonym for QList<QVariant>.

typedef QVariantMap

Synonym for QMap<QString, QVariant>.

bool qVariantCanConvert ( const QVariant & value )

Returns true if the given value can be converted to the template type specified; otherwise returns false.

This function is equivalent to QVariant::canConvert(value). It is provided as a work-around for MSVC 6, which doesn't support member template functions.

See also QVariant::canConvert().

QVariant qVariantFromValue ( const T & value )

Returns a variant containing a copy of the given value with template type T.

This function is equivalent to QVariant::fromValue(value). It is provided as a work-around for MSVC 6, which doesn't support member template functions.

For example, a QObject pointer can be stored in a variant with the following code:

    QObject *object = getObjectFromSomewhere();
    QVariant data = qVariantFromValue(object);

See also QVariant::fromValue().

void qVariantSetValue ( QVariant & variant, const T & value )

Sets the contents of the given variant to a copy of the value with the specified template type T.

This function is equivalent to QVariant::setValue(value). It is provided as a work-around for MSVC 6, which doesn't support member template functions.

See also QVariant::setValue().

T qVariantValue ( const QVariant & value )

Returns the given value converted to the template type T.

This function is equivalent to QVariant::value<T>(value). It is provided as a work-around for MSVC 6, which doesn't support member template functions.

See also QVariant::value() and qvariant_cast().

T qvariant_cast ( const QVariant & value )

Returns the given value converted to the template type T.

This function is equivalent to qVariantValue().

See also qVariantValue() and QVariant::value().

bool operator!= ( const QVariant & v1, const QVariant & v2 )

This is an overloaded member function, provided for convenience.

Returns false if v1 and v2 are equal; otherwise returns true.

Warning: This function doesn't support custom types registered with qRegisterMetaType().

bool operator== ( const QVariant & v1, const QVariant & v2 )

This is an overloaded member function, provided for convenience.

Returns true if v1 and v2 are equal; otherwise returns false.

Warning: This function doesn't support custom types registered with qRegisterMetaType().

Publicité

Best Of

Actualités les plus lues

Semaine
Mois
Année

Le Qt Quarterly au hasard

Logo

Des apparences personnalisées utilisant les feuilles de style

Qt Quarterly est la revue trimestrielle proposée par Nokia et à destination des développeurs Qt. Ces articles d'une grande qualité technique sont rédigés par des experts Qt. Lire l'article.

Communauté

Ressources

Liens utiles

Contact

  • Vous souhaitez rejoindre la rédaction ou proposer un tutoriel, une traduction, une question... ? Postez dans le forum Contribuez ou contactez-nous par MP ou par email (voir en bas de page).

Qt dans le magazine

Cette page est une traduction d'une page de la documentation de Qt, écrite par Nokia Corporation and/or its subsidiary(-ies). Les éventuels problèmes résultant d'une mauvaise traduction ne sont pas imputables à Nokia. Qt 4.1
Copyright © 2012 Developpez LLC. Tous droits réservés Developpez LLC. Aucune reproduction, même partielle, ne peut être faite de ce site et de l'ensemble de son contenu : textes, documents et images sans l'autorisation expresse de Developpez LLC. Sinon, vous encourez selon la loi jusqu'à 3 ans de prison et jusqu'à 300 000 E de dommages et intérêts. Cette page est déposée à la SACD.
Vous avez déniché une erreur ? Un bug ? Une redirection cassée ? Ou tout autre problème, quel qu'il soit ? Ou bien vous désirez participer à ce projet de traduction ? N'hésitez pas à nous contacter ou par MP !
 
 
 
 
Partenaires

Hébergement Web