QVariant 类

QVariant 类举动像最常见 Qt 数据类型的并集。 更多...

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

公共函数

  QVariant (QVariant && other )
  QVariant (const QPersistentModelIndex & val )
  QVariant (const QModelIndex & val )
  QVariant (const QJsonDocument & val )
  QVariant (const QJsonArray & val )
  QVariant (const QJsonObject & val )
  QVariant (const QJsonValue & val )
  QVariant (const QUrl & val )
  QVariant (const QUuid & val )
  QVariant (const QEasingCurve & val )
  QVariant (const QRegularExpression & re )
  QVariant (const QLocale & l )
  QVariant (const QRectF & val )
  QVariant (const QRect & val )
  QVariant (const QLineF & val )
  QVariant (const QLine & val )
  QVariant (const QPointF & val )
  QVariant (const QPoint & val )
  QVariant (const QSizeF & val )
  QVariant (const QSize & val )
  QVariant (const QHash<QString, QVariant> & val )
  QVariant (const QMap<QString, QVariant> & val )
  QVariant (const QList<QVariant> & val )
  QVariant (const QDateTime & val )
  QVariant (QTime val )
  QVariant (QDate val )
  QVariant (QChar c )
  QVariant (const QStringList & val )
  QVariant (QLatin1String val )
  QVariant (const QString & val )
  QVariant (const QBitArray & val )
  QVariant (const QByteArray & val )
  QVariant (const char * val )
  QVariant (float val )
  QVariant (double val )
  QVariant (bool val )
  QVariant (qulonglong val )
  QVariant (qlonglong val )
  QVariant (uint val )
  QVariant (int val )
  QVariant (const QVariant & p )
  QVariant (QMetaType type , const void * copy = nullptr)
  QVariant ()
QVariant & operator= (QVariant && other )
QVariant & operator= (const QVariant & variant )
  ~QVariant ()
bool canConvert (QMetaType type ) const
bool canConvert () const
bool canView () const
void clear ()
const void * constData () const
bool convert (QMetaType targetType )
void * data ()
const void * data () const
bool isNull () const
bool isValid () const
QMetaType metaType () const
void setValue (T && value )
void setValue (const QVariant & value )
void setValue (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 ()

静态公共成员

QPartialOrdering compare (const QVariant & lhs , const QVariant & rhs )
QVariant fromStdVariant (const std::variant<Types...> & value )
QVariant fromValue (const T & value )
  QVariantHash
  QVariantList
  QVariantMap
T qvariant_cast (const QVariant & value )
bool operator!= (const QVariant & v1 , const QVariant & v2 )
bool operator== (const QVariant & v1 , const QVariant & v2 )

详细描述

由于 C++ 禁止 Union 来自包括有非默认构造函数 (或析构函数) 的类型,因此,最有趣的是 Qt 类均无法用于 Union。没有 QVariant,这将是问题对于 QObject::property () 及数据库工作等。

QVariant 对象保持单个值为单个 typeId () 每次。(某些类型是多值的,例如字符串列表) 可以找出由变体保持的 T 类型,将其转换为不同类型使用 convert (),使用某一 toT() 函数获取其值 (如 toSize ()),和校验类型是否可以被转换成特定类型使用 canConvert ().

方法命名 toT() (如: toInt (), toString ()) 为 const。若要求存储类型,它们返回存储对象的副本。若要求可以从存储类型生成的类型,toT() 拷贝-转换并保持对象本身不变。若要求无法从存储类型生成的类型,结果从属类型;见函数文档编制了解细节。

这里是演示 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
					

甚至可以存储 QList <QVariant> 和 QMap < QString ,QVariant> 值在变体中,因此可以轻松构造任意类型的任何复杂数据结构。这是非常强大且万能,但可能证明内存更少且速度比在标准数据结构中存储特定类型更快。

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 枚举。见 创建自定义 Qt 类型 了解细节。

有关 GUI 类型的说明

因为 QVariant 是 Qt Core 模块的一部分,所以它无法提供对 Qt GUI 中定义的数据类型的转换函数,譬如 QColor , QImage ,和 QPixmap 。换句话说,没有 toColor() 函数。取而代之,可以使用 QVariant::value () 或 qvariant_cast () 模板函数。例如:

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

反向转换 (如,从 QColor to QVariant) is automatic for all data types supported by QVariant, including GUI-related types:

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

连续使用 canConvert() 和 convert()

当使用 canConvert () 和 convert () 连续,它是可能的对于 canConvert () 会返回 true,但 convert () 会返回 false。通常,这是因为 canConvert () 仅报告 QVariant 在给定合适数据类型之间转换的一般能力;提供实际无法转换的数据,仍是可能的。

例如, 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.

另请参阅 QMetaType .

成员函数文档编制

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.

另请参阅 QMetaType .

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

另请参阅 metaType ().

[since 5.2] QVariant:: QVariant ( QVariant && other )

移动构造 QVariant 实例,使之指向同一对象如 other 所指向的。

该函数在 Qt 5.2 引入。

[since 5.5] QVariant:: QVariant (const QPersistentModelIndex & val )

构造新变体采用 QPersistentModelIndex 值, val .

该函数在 Qt 5.5 引入。

[since 5.0] QVariant:: QVariant (const QModelIndex & val )

构造新变体采用 QModelIndex 值, val .

该函数在 Qt 5.0 引入。

[since 5.0] QVariant:: QVariant (const QJsonDocument & val )

构造新变体采用 JSON 文档值 val .

该函数在 Qt 5.0 引入。

[since 5.0] QVariant:: QVariant (const QJsonArray & val )

构造新变体采用 JSON 数组值 val .

该函数在 Qt 5.0 引入。

[since 5.0] QVariant:: QVariant (const QJsonObject & val )

构造新变体采用 JSON 对象值 val .

该函数在 Qt 5.0 引入。

[since 5.0] QVariant:: QVariant (const QJsonValue & val )

构造新变体采用 JSON 值 val .

该函数在 Qt 5.0 引入。

QVariant:: QVariant (const QUrl & val )

构造新变体采用 URL 值 val .

[since 5.0] QVariant:: QVariant (const QUuid & val )

构造新变体采用 UUID (通用唯一标识符) 值 val .

该函数在 Qt 5.0 引入。

QVariant:: QVariant (const QEasingCurve & val )

构造新变体采用缓和曲线值 val .

[since 5.0] QVariant:: QVariant (const QRegularExpression & re )

构造新变体采用正则表达式值 re .

该函数在 Qt 5.0 引入。

QVariant:: QVariant (const QLocale & l )

构造新变体采用区域设置值 l .

QVariant:: QVariant (const QRectF & val )

Constructs a new variant with a rect value of val .

QVariant:: QVariant (const QRect & val )

Constructs a new variant with a rect value of val .

QVariant:: QVariant (const QLineF & val )

Constructs a new variant with a line value of val .

QVariant:: QVariant (const QLine & val )

Constructs a new variant with a line value of val .

QVariant:: QVariant (const QPointF & val )

Constructs a new variant with a point value of val .

QVariant:: QVariant (const QPoint & val )

Constructs a new variant with a point value of val .

QVariant:: QVariant (const QSizeF & val )

Constructs a new variant with a size value of val .

QVariant:: QVariant (const QSize & val )

Constructs a new variant with a size value of val .

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

Constructs a new variant with a hash of QVariant s, val .

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

Constructs a new variant with a map of QVariant s, val .

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

Constructs a new variant with a list value, val .

QVariant:: QVariant (const QDateTime & val )

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

QVariant:: QVariant ( QTime val )

Constructs a new variant with a time value, val .

QVariant:: QVariant ( QDate val )

Constructs a new variant with a date value, val .

QVariant:: QVariant ( QChar c )

Constructs a new variant with a char value, c .

QVariant:: QVariant (const QStringList & val )

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

QVariant:: QVariant ( QLatin1String val )

Constructs a new variant with a string value, val .

QVariant:: QVariant (const QString & val )

Constructs a new variant with a string value, val .

QVariant:: QVariant (const QBitArray & val )

Constructs a new variant with a bitarray value, val .

QVariant:: QVariant (const QByteArray & val )

Constructs a new variant with a bytearray 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 QString assuming UTF-8 encoding on the input val .

注意, val is converted to a QString for storing in the variant and QVariant::userType () 会返回 QMetaType::QString for the variant.

可以禁用此运算符通过定义 QT_NO_CAST_FROM_ASCII when you compile your applications.

QVariant:: QVariant ( float val )

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

QVariant:: QVariant ( double val )

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

QVariant:: QVariant ( bool val )

Constructs a new variant with a boolean value, val .

QVariant:: QVariant ( qulonglong val )

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

QVariant:: QVariant ( qlonglong val )

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

QVariant:: QVariant ( uint val )

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

QVariant:: QVariant ( int val )

Constructs a new variant with an integer value, val .

QVariant:: QVariant (const QVariant & p )

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

QVariant:: QVariant ( QMetaType type , const void * copy = nullptr)

Constructs variant of type type , and initializes with copy if copy 不是 nullptr .

Note that you have to pass the address of the variable 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 ,和 QMetaType::QObjectStar .

另请参阅 QVariant::fromValue () 和 QMetaType::Type .

QVariant:: QVariant ()

构造无效变体。

[since 5.2] QVariant &QVariant:: operator= ( QVariant && other )

移动赋值 other 到此 QVariant 实例。

该函数在 Qt 5.2 引入。

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

Assigns the value of the variant variant to this variant.

QVariant:: ~QVariant ()

销毁 QVariant 和包含对象。

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

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

返回 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.

该函数在 Qt 6.0 引入。

另请参阅 QMetaType::canConvert ().

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

返回 true 若可以将变体转换成模板类型 T ,否则 false。

范例:

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
					

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 宏。

另请参阅 convert ().

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

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

另请参阅 value ().

void QVariant:: clear ()

将此变体转换成类型 QMetaType::UnknownType 并释放任何使用资源。

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

比较对象在 lhs and rhs for ordering.

返回 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 ,分别。

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.

注意: : If a numeric comparison is done and at least one value is NaN, QPartialOrdering::Unordered 被返回。

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.

该函数在 Qt 6.0 引入。

另请参阅 QMetaType::compare () 和 QMetaType::isOrdered ().

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

将变体铸造成请求类型, 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).

返回 true if the current type of the variant was successfully cast; otherwise returns false .

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 宏。

注意: 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 .

该函数在 Qt 6.0 引入。

另请参阅 canConvert () 和 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 QVariant will not be null after the call.

另请参阅 QMetaType .

[static, since 5.11] template <typename Types> QVariant QVariant:: fromStdVariant (const std::variant < 类型 ...> & value )

返回 QVariant with the type and value of the active variant of value . If the active type is std::monostate a default QVariant 被返回。

注意: 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.

该函数在 Qt 5.11 引入。

另请参阅 fromValue ().

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

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

范例:

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

注意: If you are working with custom types, you should use the Q_DECLARE_METATYPE () macro to register your custom type.

另请参阅 setValue () 和 value ().

bool QVariant:: isNull () const

返回 true if this is a null variant, false otherwise.

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

注意: 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.

另请参阅 convert ().

bool QVariant:: isValid () const

返回 true if the storage type of this variant is not QMetaType::UnknownType ;否则返回 false .

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

返回 QMetaType of the value stored in the variant.

该函数在 Qt 6.0 引入。

template <typename T, typename> void QVariant:: setValue ( T && value )

Stores a copy of value 。若 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.

范例:

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

另请参阅 value (), fromValue (),和 canConvert ().

void QVariant:: setValue (const QVariant & value )

拷贝 value over this QVariant . It is equivalent to simply assigning value 到此 QVariant .

void QVariant:: setValue ( QVariant && value )

移动 value over this QVariant . It is equivalent to simply move assigning value 到此 QVariant .

void QVariant:: swap ( QVariant & other )

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

QBitArray QVariant:: toBitArray () const

返回变体如 QBitArray 若变体拥有 userType () QMetaType::QBitArray ; otherwise returns an empty bit array.

另请参阅 canConvert () 和 convert ().

bool QVariant:: toBool () const

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

返回 true 若变体拥有 userType () QMetaType::Bool , QMetaType::QChar , QMetaType::Double , QMetaType::Int , QMetaType::LongLong , QMetaType::UInt ,或 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 .

另请参阅 canConvert () 和 convert ().

QByteArray QVariant:: toByteArray () const

返回变体如 QByteArray 若变体拥有 userType () QMetaType::QByteArray or QMetaType::QString (converted using QString::fromUtf8 ()); otherwise returns an empty byte array.

另请参阅 canConvert () 和 convert ().

QChar QVariant:: toChar () const

返回变体如 QChar 若变体拥有 userType () QMetaType::QChar , QMetaType::Int ,或 QMetaType::UInt ;否则返回无效 QChar .

另请参阅 canConvert () 和 convert ().

QDate QVariant:: toDate () const

返回变体如 QDate 若变体拥有 userType () QMetaType::QDate , QMetaType::QDateTime ,或 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.

另请参阅 canConvert () 和 convert ().

QDateTime QVariant:: toDateTime () const

返回变体如 QDateTime 若变体拥有 userType () QMetaType::QDateTime , QMetaType::QDate ,或 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.

另请参阅 canConvert () 和 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 ,或 QMetaType::ULongLong ;否则返回 0.0。

ok 非 null: * ok is set to true if the value could be converted to a double; otherwise * ok 被设为 false。

另请参阅 canConvert () 和 convert ().

QEasingCurve QVariant:: toEasingCurve () const

返回变体如 QEasingCurve 若变体拥有 userType () QMetaType::QEasingCurve ; otherwise returns a default easing curve.

另请参阅 canConvert () 和 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 ,或 QMetaType::ULongLong ;否则返回 0.0。

ok 非 null: * ok is set to true if the value could be converted to a double; otherwise * ok 被设为 false。

另请参阅 canConvert () 和 convert ().

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

返回变体如 QHash < QString , QVariant > if the variant has type() QMetaType::QVariantHash ; otherwise returns an empty map.

另请参阅 canConvert () 和 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 ,或 QMetaType::ULongLong ;否则返回 0。

ok 非 null: * ok is set to true if the value could be converted to an int; otherwise * ok 被设为 false。

警告: 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 ().

另请参阅 canConvert () 和 convert ().

[since 5.0] QJsonArray QVariant:: toJsonArray () const

返回变体如 QJsonArray 若变体拥有 userType () QJsonArray ; otherwise returns a default constructed QJsonArray .

该函数在 Qt 5.0 引入。

另请参阅 canConvert () 和 convert ().

[since 5.0] QJsonDocument QVariant:: toJsonDocument () const

返回变体如 QJsonDocument 若变体拥有 userType () QJsonDocument ; otherwise returns a default constructed QJsonDocument .

该函数在 Qt 5.0 引入。

另请参阅 canConvert () 和 convert ().

[since 5.0] QJsonObject QVariant:: toJsonObject () const

返回变体如 QJsonObject 若变体拥有 userType () QJsonObject ; otherwise returns a default constructed QJsonObject .

该函数在 Qt 5.0 引入。

另请参阅 canConvert () 和 convert ().

[since 5.0] QJsonValue QVariant:: toJsonValue () const

返回变体如 QJsonValue 若变体拥有 userType () QJsonValue ; otherwise returns a default constructed QJsonValue .

该函数在 Qt 5.0 引入。

另请参阅 canConvert () 和 convert ().

QLine QVariant:: toLine () const

返回变体如 QLine 若变体拥有 userType () QMetaType::QLine ;否则返回无效 QLine .

另请参阅 canConvert () 和 convert ().

QLineF QVariant:: toLineF () const

返回变体如 QLineF 若变体拥有 userType () QMetaType::QLineF ;否则返回无效 QLineF .

另请参阅 canConvert () 和 convert ().

QList < QVariant > QVariant:: toList () const

Returns the variant as a QVariantList if the variant has userType () QMetaType::QVariantList or QMetaType::QStringList ; otherwise returns an empty list.

另请参阅 canConvert () 和 convert ().

QLocale QVariant:: toLocale () const

返回变体如 QLocale 若变体拥有 userType () QMetaType::QLocale ;否则返回无效 QLocale .

另请参阅 canConvert () 和 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 ,或 QMetaType::ULongLong ;否则返回 0。

ok 非 null: * ok is set to true if the value could be converted to an int; otherwise * ok 被设为 false。

另请参阅 canConvert () 和 convert ().

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

返回变体如 QMap < QString , QVariant > if the variant has type() QMetaType::QVariantMap ; otherwise returns an empty map.

另请参阅 canConvert () 和 convert ().

[since 5.0] QModelIndex QVariant:: toModelIndex () const

返回变体如 QModelIndex 若变体拥有 userType () QModelIndex ; otherwise returns a default constructed QModelIndex .

该函数在 Qt 5.0 引入。

另请参阅 canConvert (), convert (),和 toPersistentModelIndex ().

[since 5.5] QPersistentModelIndex QVariant:: toPersistentModelIndex () const

返回变体如 QPersistentModelIndex 若变体拥有 userType () QPersistentModelIndex ; otherwise returns a default constructed QPersistentModelIndex .

该函数在 Qt 5.5 引入。

另请参阅 canConvert (), convert (),和 toModelIndex ().

QPoint QVariant:: toPoint () const

返回变体如 QPoint 若变体拥有 userType () QMetaType::QPoint or QMetaType::QPointF ; otherwise returns a null QPoint .

另请参阅 canConvert () 和 convert ().

QPointF QVariant:: toPointF () const

返回变体如 QPointF 若变体拥有 userType () QMetaType::QPoint or QMetaType::QPointF ; otherwise returns a null QPointF .

另请参阅 canConvert () 和 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 ,或 QMetaType::ULongLong ;否则返回 0.0。

ok 非 null: * ok is set to true if the value could be converted to a double; otherwise * ok 被设为 false。

另请参阅 canConvert () 和 convert ().

QRect QVariant:: toRect () const

返回变体如 QRect 若变体拥有 userType () QMetaType::QRect ;否则返回无效 QRect .

另请参阅 canConvert () 和 convert ().

QRectF QVariant:: toRectF () const

返回变体如 QRectF 若变体拥有 userType () QMetaType::QRect or QMetaType::QRectF ;否则返回无效 QRectF .

另请参阅 canConvert () 和 convert ().

[since 5.0] QRegularExpression QVariant:: toRegularExpression () const

返回变体如 QRegularExpression 若变体拥有 userType () QRegularExpression ;否则返回空 QRegularExpression .

该函数在 Qt 5.0 引入。

另请参阅 canConvert () 和 convert ().

QSize QVariant:: toSize () const

返回变体如 QSize 若变体拥有 userType () QMetaType::QSize ;否则返回无效 QSize .

另请参阅 canConvert () 和 convert ().

QSizeF QVariant:: toSizeF () const

返回变体如 QSizeF 若变体拥有 userType () QMetaType::QSizeF ;否则返回无效 QSizeF .

另请参阅 canConvert () 和 convert ().

QString QVariant:: toString () const

返回变体如 QString if the variant has a userType () 包括,但不限于:

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

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

另请参阅 canConvert () 和 convert ().

QStringList QVariant:: toStringList () const

返回变体如 QStringList 若变体拥有 userType () QMetaType::QStringList , QMetaType::QString ,或 QMetaType::QVariantList of a type that can be converted to QString ; otherwise returns an empty list.

另请参阅 canConvert () 和 convert ().

QTime QVariant:: toTime () const

返回变体如 QTime 若变体拥有 userType () QMetaType::QTime , QMetaType::QDateTime ,或 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.

另请参阅 canConvert () 和 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 ,或 QMetaType::ULongLong ;否则返回 0。

ok 非 null: * ok is set to true if the value could be converted to an unsigned int; otherwise * ok 被设为 false。

警告: 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 ().

另请参阅 canConvert () 和 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 ,或 QMetaType::UInt ;否则返回 0。

ok 非 null: * ok is set to true if the value could be converted to an int; otherwise * ok 被设为 false。

另请参阅 canConvert () 和 convert ().

QUrl QVariant:: toUrl () const

返回变体如 QUrl 若变体拥有 userType () QMetaType::QUrl ;否则返回无效 QUrl .

另请参阅 canConvert () 和 convert ().

[since 5.0] QUuid QVariant:: toUuid () const

返回变体如 QUuid if the variant has type() QMetaType::QUuid , QMetaType::QByteArray or QMetaType::QString ;否则返回默认构造的 QUuid .

该函数在 Qt 5.0 引入。

另请参阅 canConvert () 和 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 ",或 "QVariantList"。无效变体返回 0。

template <typename T> T QVariant:: value () const

返回的存储值被转换为模板类型 T 。调用 canConvert () 以找出是否可以转换类型。若无法转换值, 默认构造值 将被返回。

若类型 T 支持通过 QVariant ,此函数的行为准确如 toString (), toInt () 等。

范例:

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
					

QVariant contains a pointer to a type derived from QObject then T may be any QObject type. If the pointer stored in the QVariant 可以是 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 宏。

QVariant contains a sequential container and T is QVariantList, the elements of the container will be converted into QVariant s 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;
    }
}
					

另请参阅 setValue (), fromValue (), canConvert (),和 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 。调用 canConvert () to find out whether a type can be converted. If the value can neither be viewed nor converted, a 默认构造值 将被返回。

另请参阅 canView () 和 Q_DECLARE_SEQUENTIAL_CONTAINER_METATYPE ().

相关非成员

[alias] QVariantHash

同义词 QHash < QString , QVariant >.

[alias] QVariantList

同义词 QList < QVariant >.

[alias] QVariantMap

同义词 QMap < QString , QVariant >.

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

返回给定 value 被转换成模板类型 T .

此函数相当于 QVariant::value ().

另请参阅 QVariant::value ().

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

返回 false if v1 and v2 相等;否则返回 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.

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

返回 true if v1 and v2 相等;否则返回 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.