- Qt 6.8
- Qt Core
- C++ Classes
- QVariant
- Qt 6.8.3 Reference Documentation

# QVariant Class

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

Header: | `#include <QVariant>`
CMake: | `find_package(Qt6 REQUIRED COMPONENTS Core)` `target_link_libraries(mytarget PRIVATE Qt6::Core)`
qmake: | `QT += core`

- List of all members, including inherited members
- Deprecated members
- QVariant is part of Implicitly Shared Classes.

This class is equality-comparable.

## Public Functions

| QVariant()
| QVariant(QChar c)
| QVariant(const char *val)
| QVariant(double val)
| QVariant(float val)
| QVariant(int val)
| QVariant(qlonglong val)
| QVariant(qulonglong val)
| QVariant(uint val)
| QVariant(QMetaType type, const void *copy = nullptr)
`(since 6.6)` | QVariant(std::in_place_type_t<T>, Args &&... args)
`(since 6.6)` | QVariant(std::in_place_type_t<T>, std::initializer_list<U> il, Args &&... args)
| QVariant(QDate val)
| QVariant(QLatin1StringView val)
| QVariant(QLine val)
| QVariant(QLineF val)
| QVariant(QPoint val)
| QVariant(QPointF val)
| QVariant(QRect val)
| QVariant(QRectF val)
| QVariant(QSize val)
| QVariant(QSizeF val)
| QVariant(QTime val)
| QVariant(QUuid val)
| QVariant(bool val)
| QVariant(const QBitArray &val)
| QVariant(const QByteArray &val)
| QVariant(const QDateTime &val)
| QVariant(const QEasingCurve &val)
| QVariant(const QHash<QString, QVariant> &val)
| QVariant(const QJsonArray &val)
| QVariant(const QJsonDocument &val)
| QVariant(const QJsonObject &val)
| QVariant(const QJsonValue &val)
| QVariant(const QList<QVariant> &val)
| QVariant(const QLocale &l)
| QVariant(const QMap<QString, QVariant> &val)
| QVariant(const QModelIndex &val)
| QVariant(const QPersistentModelIndex &val)
| QVariant(const QRegularExpression &re)
| QVariant(const QString &val)
| QVariant(const QStringList &val)
| QVariant(const QUrl &val)
| QVariant(const QVariant &p)
| QVariant(QVariant &&other)
| ~QVariant()
bool | canConvert() const
`(since 6.0)` bool | canConvert(QMetaType type) const
bool | canView() const
void | clear()
const void * | constData() const
`(since 6.0)` bool | convert(QMetaType targetType)
void * | data()
const void * | data() const
`(since 6.6)` T & | emplace(Args &&... args)
`(since 6.6)` T & | emplace(std::initializer_list<U> list, Args &&... args)
bool | isNull() const
bool | isValid() const
`(since 6.0)` QMetaType | metaType() const
void | setValue(QVariant &&value)
void | setValue(T &&value)
void | setValue(const QVariant &value)
void | swap(QVariant &other)
QBitArray | toBitArray() const
bool | toBool() const
QByteArray | toByteArray() const
QChar | toChar() const
QDate | toDate() const
QDateTime | toDateTime() const
double | toDouble(bool *ok = nullptr) const
QEasingCurve | toEasingCurve() const
float | toFloat(bool *ok = nullptr) const
QHash<QString, QVariant> | toHash() const
int | toInt(bool *ok = nullptr) const
QJsonArray | toJsonArray() const
QJsonDocument | toJsonDocument() const
QJsonObject | toJsonObject() const
QJsonValue | toJsonValue() const
QLine | toLine() const
QLineF | toLineF() const
QList<QVariant> | toList() const
QLocale | toLocale() const
qlonglong | toLongLong(bool *ok = nullptr) const
QMap<QString, QVariant> | toMap() const
QModelIndex | toModelIndex() const
QPersistentModelIndex | toPersistentModelIndex() const
QPoint | toPoint() const
QPointF | toPointF() const
qreal | toReal(bool *ok = nullptr) const
QRect | toRect() const
QRectF | toRectF() const
QRegularExpression | toRegularExpression() const
QSize | toSize() const
QSizeF | toSizeF() const
QString | toString() const
QStringList | toStringList() const
QTime | toTime() const
uint | toUInt(bool *ok = nullptr) const
qulonglong | toULongLong(bool *ok = nullptr) const
QUrl | toUrl() const
QUuid | toUuid() const
int | typeId() const
const char * | typeName() const
int | userType() const
T | value() const &
T | view()
QVariant & | operator=(QVariant &&other)
QVariant & | operator=(const QVariant &variant)

## Static Public Members

`(since 6.0)` QPartialOrdering | compare(const QVariant &lhs, const QVariant &rhs)
`(since 6.7)` QVariant | fromMetaType(QMetaType type, const void *copy = nullptr)
QVariant | fromStdVariant(const std::variant<Types...> &value)
`(since 6.6)` QVariant | fromStdVariant(std::variant<Types...> &&value)
QVariant | fromValue(const T &value)
`(since 6.6)` QVariant | fromValue(T &&value)

## Related Non-Members

| QVariantHash
| QVariantList
| QVariantMap
`(since 6.6)` T & | get(QVariant &v)
`(since 6.6)` T && | get(QVariant &&v)
`(since 6.6)` const T & | get(const QVariant &v)
`(since 6.6)` const T && | get(const QVariant &&v)
`(since 6.6)` T * | get_if(QVariant *v)
`(since 6.6)` const T * | get_if(const QVariant *v)
T | qvariant_cast(const QVariant &value)
`(since 6.7)` T | qvariant_cast(QVariant &&value)
bool | operator!=(const QVariant &lhs, const QVariant &rhs)
QDataStream & | operator<<(QDataStream &s, const QVariant &p)
bool | operator==(const QVariant &lhs, const QVariant &rhs)
QDataStream & | operator>>(QDataStream &s, QVariant &p)

## Detailed Description

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 typeId() at a time. (Some types 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(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 holds the value 223
     v = QVariant(QStringList());    // The variant now holds a 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. A variant is null if the variant contains no initialized value, or contains a null pointer.

     QVariant x;                                // x.isNull() == true
     QVariant y = QVariant::fromValue(nullptr); // y.isNull() == true

QVariant can be extended to support other types than those mentioned in the QMetaType::Type enum. See Creating Custom Qt Types for details.

### A Note on GUI Types

Because QVariant is part of the Qt Core module, it cannot provide conversion functions to data types defined in Qt GUI, such as QColor, QImage, and QPixmap. In other words, there is no `toColor()` function. Instead, you can use the QVariant::value() or the qvariant_cast() 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(QMetaType::fromType<int>())` 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.

## Member Function Documentation

### int QVariant::typeId() const

### int QVariant::userType() const

Returns the storage type of the value stored in the variant. This is the same as metaType().id().

See also metaType().

### const void *QVariant::constData() const

### const void *QVariant::data() const

Returns a pointer to the contained object as a generic void* that cannot be written to.

See also get_if() and QMetaType.

### `[noexcept]` QVariant::QVariant()

Constructs an invalid variant.

### `[noexcept]` QVariant::QVariant(QChar c)

Constructs a new variant with a char value, c.

### QVariant::QVariant(const char *val)

Constructs a new variant with a string value of val. The variant creates a deep copy of val into a QString assuming UTF-8 encoding on the input val.

Note that val is converted to a QString for storing in the variant and QVariant::userType() will return QMetaType::QString for the variant.

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

### `[noexcept]` QVariant::QVariant(double val)

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

### `[noexcept]` QVariant::QVariant(float val)

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

### `[noexcept]` QVariant::QVariant(int val)

Constructs a new variant with an integer value, val.

### `[noexcept]` QVariant::QVariant(qlonglong val)

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

### `[noexcept]` QVariant::QVariant(qulonglong val)

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

### `[noexcept]` QVariant::QVariant(uint val)

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

### `[explicit]` QVariant::QVariant(QMetaType type, const void *copy = nullptr)

Constructs a variant of type type, and initializes it with a copy of `*copy` if copy is not `nullptr` (in which case, copy must point to an object of type type).

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

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

If type does not support copy construction and copy is not `nullptr`, the variant will be invalid. Similarly, if copy is `nullptr` and type does not support default construction, the variant will be invalid.

See also QVariant::fromMetaType, QVariant::fromValue(), and QMetaType::Type.

### `[explicit noexcept(...), since 6.6]` template <typename T, typename... Args, QVariant::if_constructible<T, Args...> = true> QVariant::QVariant(std::in_place_type_t<T>, Args &&... args)

Constructs a new variant containing a value of type `T`. The contained value is is initialized with the arguments `std::forward<Args>(args)...`.

This overload only participates in overload resolution if `T` can be constructed from args.

This constructor is provided for STL/std::any compatibility.

This is an overloaded function.

This function was introduced in Qt 6.6.

Note: This function is noexcept when `is_noexcept_constructible<q20::remove_cvref_t<T>, Args...>::value` is `true`.

### `[explicit noexcept(...), since 6.6]` template <typename T, typename U, typename... Args, QVariant::if_constructible<T, std::initializer_list<U> &, Args...> = true> QVariant::QVariant(std::in_place_type_t<T>, std::initializer_list<U> il, Args &&... args)

This is an overloaded function.

This overload exists to support types with constructors taking an `initializer_list`. It behaves otherwise equivalent to the non-initializer list `in_place_type_t` overload.

This function was introduced in Qt 6.6.

Note: This function is noexcept when `is_noexcept_constructible<q20::remove_cvref_t<T>, std::initializer_list<U> &, Args... >::value` is `true`.

### `[noexcept]` QVariant::QVariant(QDate val)

Constructs a new variant with a date value, val.

### QVariant::QVariant(QLatin1StringView val)

Constructs a new variant with a QString value from the Latin-1 string viewed by val.

### `[noexcept(...)]` QVariant::QVariant(QLine val)

Constructs a new variant with a line value of val.

Note: This function is noexcept when `Private::FitsInInternalSize<sizeof(int) * 4>` is `true`.

### `[noexcept(...)]` QVariant::QVariant(QLineF val)

Constructs a new variant with a line value of val.

Note: This function is noexcept when `Private::FitsInInternalSize<sizeof(qreal) * 4>` is `true`.

### `[noexcept]` QVariant::QVariant(QPoint val)

Constructs a new variant with a point value of val.

### `[noexcept(...)]` QVariant::QVariant(QPointF val)

Constructs a new variant with a point value of val.

Note: This function is noexcept when `Private::FitsInInternalSize<sizeof(qreal) * 2>` is `true`.

### `[noexcept(...)]` QVariant::QVariant(QRect val)

Constructs a new variant with a rect value of val.

Note: This function is noexcept when `Private::FitsInInternalSize<sizeof(int) * 4>` is `true`.

### `[noexcept(...)]` QVariant::QVariant(QRectF val)

Constructs a new variant with a rect value of val.

Note: This function is noexcept when `Private::FitsInInternalSize<sizeof(qreal) * 4>` is `true`.

### `[noexcept]` QVariant::QVariant(QSize val)

Constructs a new variant with a size value of val.

### `[noexcept(...)]` QVariant::QVariant(QSizeF val)

Constructs a new variant with a size value of val.

Note: This function is noexcept when `Private::FitsInInternalSize<sizeof(qreal) * 2>` is `true`.

### `[noexcept]` QVariant::QVariant(QTime val)

Constructs a new variant with a time value, val.

### `[noexcept(...)]` QVariant::QVariant(QUuid val)

Constructs a new variant with an uuid value, val.

Note: This function is noexcept when `Private::FitsInInternalSize<16>` is `true`.

### `[noexcept]` QVariant::QVariant(bool val)

Constructs a new variant with a boolean value, val.

### `[noexcept]` QVariant::QVariant(const QBitArray &val)

Constructs a new variant with a bitarray value, val.

### `[noexcept]` QVariant::QVariant(const QByteArray &val)

Constructs a new variant with a bytearray value, val.

### `[noexcept]` QVariant::QVariant(const QDateTime &val)

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

### QVariant::QVariant(const QEasingCurve &val)

Constructs a new variant with an easing curve value, val.

### `[noexcept]` QVariant::QVariant(const QHash<QString, QVariant> &val)

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

### `[noexcept]` QVariant::QVariant(const QJsonArray &val)

Constructs a new variant with a json array value, val.

### QVariant::QVariant(const QJsonDocument &val)

Constructs a new variant with a json document value, val.

### `[noexcept]` QVariant::QVariant(const QJsonObject &val)

Constructs a new variant with a json object value, val.

### `[noexcept(...)]` QVariant::QVariant(const QJsonValue &val)

Constructs a new variant with a json value, val.

Note: This function is noexcept when `Private::FitsInInternalSize<sizeof(CborValueStandIn)>` is `true`.

### `[noexcept]` QVariant::QVariant(const QList<QVariant> &val)

Constructs a new variant with a list value, val.

### `[noexcept]` QVariant::QVariant(const QLocale &l)

Constructs a new variant with a locale value, l.

### `[noexcept]` QVariant::QVariant(const QMap<QString, QVariant> &val)

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

### `[noexcept(...)]` QVariant::QVariant(const QModelIndex &val)

Constructs a new variant with a QModelIndex value, val.

Note: This function is noexcept when `Private::FitsInInternalSize<8 + 2 * sizeof(quintptr)>` is `true`.

### QVariant::QVariant(const QPersistentModelIndex &val)

Constructs a new variant with a QPersistentModelIndex value, val.

### `[noexcept]` QVariant::QVariant(const QRegularExpression &re)

Constructs a new variant with the regular expression value re.

### `[noexcept]` QVariant::QVariant(const QString &val)

Constructs a new variant with a string value, val.

### `[noexcept]` QVariant::QVariant(const QStringList &val)

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

### `[noexcept]` QVariant::QVariant(const QUrl &val)

Constructs a new variant with a url value of val.

### QVariant::QVariant(const QVariant &p)

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

### `[noexcept]` QVariant::QVariant(QVariant &&other)

Move-constructs a QVariant instance, making it point at the same object that other was pointing to.

### `[noexcept]` QVariant::~QVariant()

Destroys the QVariant and the contained object.

### template <typename T> bool QVariant::canConvert() const

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

A QVariant containing a pointer to a type derived from QObject will also return true for this function if a qobject_cast to the template type `T` would succeed. Note that this only works for QObject subclasses which use the Q_OBJECT macro.

See also convert().

### `[since 6.0]` bool QVariant::canConvert(QMetaType type) const

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

This function was introduced in Qt 6.0.

See also QMetaType::canConvert().

### template <typename T> bool QVariant::canView() const

Returns `true` if a mutable view of the template type `T` can be created on this variant, otherwise `false`.

See also value().

### void QVariant::clear()

Convert this variant to type QMetaType::UnknownType and free up any resources used.

### `[static, since 6.0]` QPartialOrdering QVariant::compare(const QVariant &lhs, const QVariant &rhs)

Compares the objects at lhs and rhs for ordering.

Returns QPartialOrdering::Unordered if comparison is not supported or the values are unordered. Otherwise, returns QPartialOrdering::Less, QPartialOrdering::Equivalent or QPartialOrdering::Greater if lhs is less than, equivalent to or greater than rhs, respectively.

If the variants contain data with a different metatype, the values are considered unordered unless they are both of numeric or pointer types, where regular numeric or pointer comparison rules will be used.

Note: : If a numeric comparison is done and at least one value is NaN, QPartialOrdering::Unordered is returned.

If both variants contain data of the same metatype, the method will use the QMetaType::compare method to determine the ordering of the two variants, which can also indicate that it can't establish an ordering between the two values.

This function was introduced in Qt 6.0.

See also QMetaType::compare() and QMetaType::isOrdered().

### `[since 6.0]` bool QVariant::convert(QMetaType targetType)

Casts the variant to the requested type, targetType. If the cast cannot be done, the variant is still changed to the requested type, but is left in a cleared null state similar to that constructed by QVariant(Type).

Returns `true` if the current type of the variant was successfully cast; otherwise returns `false`.

A QVariant containing a pointer to a type derived from QObject will also convert and return true for this function if a qobject_cast to the type described by targetType would succeed. Note that this only works for QObject subclasses which use the Q_OBJECT macro.

Note: converting QVariants that are null due to not being initialized or having failed a previous conversion will always fail, changing the type, remaining null, and returning `false`.

This function was introduced in Qt 6.0.

See also canConvert() and clear().

### void *QVariant::data()

Returns a pointer to the contained object as a generic void* that can be written to.

This function detaches the QVariant. When called on a null-QVariant, the QVariant will not be null after the call.

See also get_if() and QMetaType.

### `[since 6.6]` template <typename T, typename... Args, QVariant::if_constructible<T, Args...> = true> T &QVariant::emplace(Args &&... args)

Replaces the object currently held in `*this` with an object of type `T`, constructed from args`...`. If `*this` was non-null, the previously held object is destroyed first. If possible, this method will reuse memory allocated by the QVariant. Returns a reference to the newly-created object.

This function was introduced in Qt 6.6.

### `[since 6.6]` template <typename T, typename U, typename... Args, QVariant::if_constructible<T, std::initializer_list<U> &, Args...> = true> T &QVariant::emplace(std::initializer_list<U> list, Args &&... args)

This is an overloaded function.

This overload exists to support types with constructors taking an `initializer_list`. It behaves otherwise equivalent to the non-initializer list overload.

This function was introduced in Qt 6.6.

### `[static, since 6.7]` QVariant QVariant::fromMetaType(QMetaType type, const void *copy = nullptr)

Creates a variant of type type, and initializes it with a copy of `*copy` if copy is not `nullptr` (in which case, copy must point to an object of type type).

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

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

If type does not support copy construction and copy is not `nullptr`, the variant will be invalid. Similarly, if copy is `nullptr` and type does not support default construction, the variant will be invalid.

Returns the QVariant created as described above.

This function was introduced in Qt 6.7.

See also QVariant::fromValue() and QMetaType::Type.

### `[static]` template <typename... Types> QVariant QVariant::fromStdVariant(const std::variant<Types...> &value)

Returns a QVariant with the type and value of the active variant of value. If the active type is std::monostate a default QVariant is returned.

Note: With this method you do not need to register the variant as a Qt metatype, since the std::variant is resolved before being stored. The component types should be registered however.

See also fromValue().

### `[static, since 6.6]` template <typename... Types> QVariant QVariant::fromStdVariant(std::variant<Types...> &&value)

This is an overloaded function.

This function was introduced in Qt 6.6.

### `[static]` template <typename T> QVariant QVariant::fromValue(const T &value)

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

Example:

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

See also setValue() and value().

### `[static, since 6.6]` template <typename T, QVariant::if_rvalue<T> = true> QVariant QVariant::fromValue(T &&value)

This is an overloaded function.

This function was introduced in Qt 6.6.

### bool QVariant::isNull() const

Returns `true` if this is a null variant, false otherwise.

A variant is considered null if it contains no initialized value or a null pointer.

Note: This behavior has been changed from Qt 5, where isNull() would also return true if the variant contained an object of a builtin type with an isNull() method that returned true for that object.

See also convert().

### bool QVariant::isValid() const

Returns `true` if the storage type of this variant is not QMetaType::UnknownType; otherwise returns `false`.

### `[since 6.0]` QMetaType QVariant::metaType() const

Returns the QMetaType of the value stored in the variant.

This function was introduced in Qt 6.0.

### void QVariant::setValue(QVariant &&value)

Moves value over this QVariant. It is equivalent to simply move assigning value to this QVariant.

See also value().

### template <typename T, typename = std::enable_if_t<!std::is_same_v<std::decay_t<T>, QVariant>>> void QVariant::setValue(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>();

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

### void QVariant::setValue(const QVariant &value)

Copies value over this QVariant. It is equivalent to simply assigning value to this QVariant.

### `[noexcept]` void QVariant::swap(QVariant &other)

Swaps this variant with other. This operation is very fast and never fails.

### QBitArray QVariant::toBitArray() const

Returns the variant as a QBitArray if the variant has userType() QMetaType::QBitArray; 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 userType() Bool.

Returns `true` if the variant has userType() QMetaType::Bool, QMetaType::QChar, QMetaType::Double, QMetaType::Int, QMetaType::LongLong, QMetaType::UInt, or QMetaType::ULongLong and the value is non-zero, or if the variant has type QMetaType::QString or QMetaType::QByteArray and its lower-case content is not one of the following: 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 userType() QMetaType::QByteArray or QMetaType::QString (converted using QString::fromUtf8()); 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 userType() QMetaType::QChar, QMetaType::Int, or QMetaType::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 userType() QMetaType::QDate, QMetaType::QDateTime, or QMetaType::QString; otherwise returns an invalid date.

If the type() is QMetaType::QString, 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 userType() QMetaType::QDateTime, QMetaType::QDate, or QMetaType::QString; otherwise returns an invalid date/time.

If the type() is QMetaType::QString, 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 = nullptr) const

Returns the variant as a double if the variant has userType() QMetaType::Double, QMetaType::Float, QMetaType::Bool, QMetaType::QByteArray, QMetaType::Int, QMetaType::LongLong, QMetaType::QString, QMetaType::UInt, or QMetaType::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().

### QEasingCurve QVariant::toEasingCurve() const

Returns the variant as a QEasingCurve if the variant has userType() QMetaType::QEasingCurve; otherwise returns a default easing curve.

See also canConvert() and convert().

### float QVariant::toFloat(bool *ok = nullptr) const

Returns the variant as a float if the variant has userType() QMetaType::Double, QMetaType::Float, QMetaType::Bool, QMetaType::QByteArray, QMetaType::Int, QMetaType::LongLong, QMetaType::QString, QMetaType::UInt, or QMetaType::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().

### QHash<QString, QVariant> QVariant::toHash() const

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

See also canConvert() and convert().

### int QVariant::toInt(bool *ok = nullptr) const

Returns the variant as an int if the variant has userType() QMetaType::Int, QMetaType::Bool, QMetaType::QByteArray, QMetaType::QChar, QMetaType::Double, QMetaType::LongLong, QMetaType::QString, QMetaType::UInt, or QMetaType::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 QMetaType::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().

See also canConvert() and convert().

### QJsonArray QVariant::toJsonArray() const

Returns the variant as a QJsonArray if the variant has userType() QJsonArray; otherwise returns a default constructed QJsonArray.

See also canConvert() and convert().

### QJsonDocument QVariant::toJsonDocument() const

Returns the variant as a QJsonDocument if the variant has userType() QJsonDocument; otherwise returns a default constructed QJsonDocument.

See also canConvert() and convert().

### QJsonObject QVariant::toJsonObject() const

Returns the variant as a QJsonObject if the variant has userType() QJsonObject; otherwise returns a default constructed QJsonObject.

See also canConvert() and convert().

### QJsonValue QVariant::toJsonValue() const

Returns the variant as a QJsonValue if the variant has userType() QJsonValue; otherwise returns a default constructed QJsonValue.

See also canConvert() and convert().

### QLine QVariant::toLine() const

Returns the variant as a QLine if the variant has userType() QMetaType::QLine; otherwise returns an invalid QLine.

See also canConvert() and convert().

### QLineF QVariant::toLineF() const

Returns the variant as a QLineF if the variant has userType() QMetaType::QLineF; 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 userType() QMetaType::QVariantList. If it doesn't, QVariant will attempt to convert the type to a list and then return it. This will succeed for any type that has registered a converter to QVariantList or which was declared as a sequential container using Q_DECLARE_SEQUENTIAL_CONTAINER_METATYPE. If none of those conditions are true, this function will return an empty list.

See also canConvert() and convert().

### QLocale QVariant::toLocale() const

Returns the variant as a QLocale if the variant has userType() QMetaType::QLocale; otherwise returns an invalid QLocale.

See also canConvert() and convert().

### qlonglong QVariant::toLongLong(bool *ok = nullptr) const

Returns the variant as a long long int if the variant has userType() QMetaType::LongLong, QMetaType::Bool, QMetaType::QByteArray, QMetaType::QChar, QMetaType::Double, QMetaType::Int, QMetaType::QString, QMetaType::UInt, or QMetaType::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 QVariantMap if the variant has type() QMetaType::QVariantMap. If it doesn't, QVariant will attempt to convert the type to a map and then return it. This will succeed for any type that has registered a converter to QVariantMap or which was declared as a associative container using Q_DECLARE_ASSOCIATIVE_CONTAINER_METATYPE. If none of those conditions are true, this function will return an empty map.

See also canConvert() and convert().

### QModelIndex QVariant::toModelIndex() const

Returns the variant as a QModelIndex if the variant has userType() QModelIndex; otherwise returns a default constructed QModelIndex.

See also canConvert(), convert(), and toPersistentModelIndex().

### QPersistentModelIndex QVariant::toPersistentModelIndex() const

Returns the variant as a QPersistentModelIndex if the variant has userType() QPersistentModelIndex; otherwise returns a default constructed QPersistentModelIndex.

See also canConvert(), convert(), and toModelIndex().

### QPoint QVariant::toPoint() const

Returns the variant as a QPoint if the variant has userType() QMetaType::QPoint or QMetaType::QPointF; otherwise returns a null QPoint.

See also canConvert() and convert().

### QPointF QVariant::toPointF() const

Returns the variant as a QPointF if the variant has userType() QMetaType::QPoint or QMetaType::QPointF; otherwise returns a null QPointF.

See also canConvert() and convert().

### qreal QVariant::toReal(bool *ok = nullptr) const

Returns the variant as a qreal if the variant has userType() QMetaType::Double, QMetaType::Float, QMetaType::Bool, QMetaType::QByteArray, QMetaType::Int, QMetaType::LongLong, QMetaType::QString, QMetaType::UInt, or QMetaType::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().

### QRect QVariant::toRect() const

Returns the variant as a QRect if the variant has userType() QMetaType::QRect; otherwise returns an invalid QRect.

See also canConvert() and convert().

### QRectF QVariant::toRectF() const

Returns the variant as a QRectF if the variant has userType() QMetaType::QRect or QMetaType::QRectF; otherwise returns an invalid QRectF.

See also canConvert() and convert().

### QRegularExpression QVariant::toRegularExpression() const

Returns the variant as a QRegularExpression if the variant has userType() QRegularExpression; otherwise returns an empty QRegularExpression.

See also canConvert() and convert().

### QSize QVariant::toSize() const

Returns the variant as a QSize if the variant has userType() QMetaType::QSize; otherwise returns an invalid QSize.

See also canConvert() and convert().

### QSizeF QVariant::toSizeF() const

Returns the variant as a QSizeF if the variant has userType() QMetaType::QSizeF; otherwise returns an invalid QSizeF.

See also canConvert() and convert().

### QString QVariant::toString() const

Returns the variant as a QString if the variant has a userType() including, but not limited to:

QMetaType::QString, QMetaType::Bool, QMetaType::QByteArray, QMetaType::QChar, QMetaType::QDate, QMetaType::QDateTime, QMetaType::Double, QMetaType::Int, QMetaType::LongLong, QMetaType::QStringList, QMetaType::QTime, QMetaType::UInt, or QMetaType::ULongLong.

Calling QVariant::toString() on an unsupported variant returns an empty string.

See also canConvert() and convert().

### QStringList QVariant::toStringList() const

Returns the variant as a QStringList if the variant has userType() QMetaType::QStringList, QMetaType::QString, or QMetaType::QVariantList 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 userType() QMetaType::QTime, QMetaType::QDateTime, or QMetaType::QString; otherwise returns an invalid time.

If the type() is QMetaType::QString, 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 = nullptr) const

Returns the variant as an unsigned int if the variant has userType() QMetaType::UInt, QMetaType::Bool, QMetaType::QByteArray, QMetaType::QChar, QMetaType::Double, QMetaType::Int, QMetaType::LongLong, QMetaType::QString, or QMetaType::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 QMetaType::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().

See also canConvert() and convert().

### qulonglong QVariant::toULongLong(bool *ok = nullptr) const

Returns the variant as an unsigned long long int if the variant has type() QMetaType::ULongLong, QMetaType::Bool, QMetaType::QByteArray, QMetaType::QChar, QMetaType::Double, QMetaType::Int, QMetaType::LongLong, QMetaType::QString, or QMetaType::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 userType() QMetaType::QUrl; otherwise returns an invalid QUrl.

See also canConvert() and convert().

### QUuid QVariant::toUuid() const

Returns the variant as a QUuid if the variant has type() QMetaType::QUuid, QMetaType::QByteArray or QMetaType::QString; otherwise returns a default-constructed QUuid.

See also canConvert() and convert().

### 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.

### template <typename T> 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, a 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 = 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

If the QVariant contains a pointer to a type derived from QObject then `T` may be any QObject type. If the pointer stored in the QVariant can be qobject_cast to T, then that result is returned. Otherwise `nullptr` is returned. Note that this only works for QObject subclasses which use the Q_OBJECT macro.

If the QVariant contains a sequential container and `T` is QVariantList, the elements of the container will be converted into QVariants and returned as a QVariantList.

     QList<int> intList = {7, 11, 42};

     QVariant variant = QVariant::fromValue(intList);
     if (variant.canConvert<QVariantList>()) {
         QSequentialIterable iterable = variant.value<QSequentialIterable>();
         // Can use foreach:
         foreach (const QVariant &v, iterable) {
             qDebug() << v;
         }
         // Can use C++11 range-for:
         for (const QVariant &v : iterable) {
             qDebug() << v;
         }
         // Can use iterators:
         QSequentialIterable::const_iterator it = iterable.begin();
         const QSequentialIterable::const_iterator end = iterable.end();
         for ( ; it != end; ++it) {
             qDebug() << *it;
         }
     }

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

### template <typename T> T QVariant::view()

Returns a mutable view of template type `T` on the stored value. Call canView() to find out whether such a view is supported. If no such view can be created, returns the stored value converted to the template type `T`. Call canConvert() to find out whether a type can be converted. If the value can neither be viewed nor converted, a default-constructed value will be returned.

See also canView() and Q_DECLARE_SEQUENTIAL_CONTAINER_METATYPE().

### `[noexcept]` QVariant &QVariant::operator=(QVariant &&other)

Move-assigns other to this QVariant instance.

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

Assigns the value of the variant variant to this variant.

## Related Non-Members

### `[noexcept, since 6.6]` template <typename T> T *get_if(QVariant *v)

### `[noexcept, since 6.6]` template <typename T> const T *get_if(const QVariant *v)

If v contains an object of type `T`, returns a pointer to the contained object, otherwise returns `nullptr`.

The overload taking a mutable v detaches v: When called on a null v with matching type `T`, v will not be null after the call.

These functions are provided for compatibility with `std::variant`.

This function was introduced in Qt 6.6.

See also data().

### `[since 6.6]` template <typename T> T &get(QVariant &v)

### `[since 6.6]` template <typename T> T &&get(QVariant &&v)

### `[since 6.6]` template <typename T> const T &get(const QVariant &v)

### `[since 6.6]` template <typename T> const T &&get(const QVariant &&v)

If v contains an object of type `T`, returns a reference to the contained object, otherwise the call has undefined behavior.

The overloads taking a mutable v detach v: When called on a null v with matching type `T`, v will not be null after the call.

These functions are provided for compatibility with `std::variant`.

This function was introduced in Qt 6.6.

See also get_if() and data().

### `[alias]` QVariantHash

Synonym for QHash<QString, QVariant>.

### `[alias]` QVariantList

Synonym for QList<QVariant>.

### `[alias]` QVariantMap

Synonym for QMap<QString, QVariant>.

### template <typename T> T qvariant_cast(const QVariant &value)

Returns the given value converted to the template type `T`.

This function is equivalent to QVariant::value().

See also QVariant::value().

### `[since 6.7]` template <typename T> T qvariant_cast(QVariant &&value)

This is an overloaded function.

Returns the given value converted to the template type `T`.

This function was introduced in Qt 6.7.

### `[noexcept]` bool operator!=(const QVariant &lhs, const QVariant &rhs)

Returns `false` if lhs and rhs are equal; otherwise returns `true`.

QVariant uses the equality operator of the type() contained to check for equality.

Variants of different types will always compare as not equal with a few exceptions:

- If both types are numeric types (integers and floatins point numbers) Qt will compare those types using standard C++ type promotion rules.
- If one type is numeric and the other one a QString, Qt will try to convert the QString to a matching numeric type and if successful compare those.
- If both variants contain pointers to QObject derived types, QVariant will check whether the types are related and point to the same object.

### QDataStream &operator<<(QDataStream &s, const QVariant &p)

Writes a variant p to the stream s.

See also Format of the QDataStream operators.

### `[noexcept]` bool operator==(const QVariant &lhs, const QVariant &rhs)

Returns `true` if lhs and rhs are equal; otherwise returns `false`.

QVariant uses the equality operator of the type() contained to check for equality.

Variants of different types will always compare as not equal with a few exceptions:

- If both types are numeric types (integers and floatins point numbers) Qt will compare those types using standard C++ type promotion rules.
- If one type is numeric and the other one a QString, Qt will try to convert the QString to a matching numeric type and if successful compare those.
- If both variants contain pointers to QObject derived types, QVariant will check whether the types are related and point to the same object.

The result of the function is not affected by the result of QVariant::isNull, which means that two values can be equal even if one of them is null and another is not.

### QDataStream &operator>>(QDataStream &s, QVariant &p)

Reads a variant p from the stream s.

Note: If the stream contains types that aren't the built-in ones (see QMetaType::Type), those types must be registered using qRegisterMetaType() or QMetaType::registerType() before the variant can be properly loaded. If an unregistered type is found, QVariant will set the corrupt flag in the stream, stop processing and print a warning. For example, for QList<int> it would print the following:

> QVariant::load: unknown user type with name QList<int>

See also Format of the QDataStream operators.