1 /****************************************************************************
3 ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
6 ** This file is part of the QtCore module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and Digia. For licensing terms and
14 ** conditions see http://qt.digia.com/licensing. For further information
15 ** use the contact form at http://qt.digia.com/contact-us.
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL included in the
21 ** packaging of this file. Please review the following information to
22 ** ensure the GNU Lesser General Public License version 2.1 requirements
23 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
25 ** In addition, as a special exception, Digia gives you certain additional
26 ** rights. These rights are described in the Digia Qt LGPL Exception
27 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
29 ** GNU General Public License Usage
30 ** Alternatively, this file may be used under the terms of the GNU
31 ** General Public License version 3.0 as published by the Free Software
32 ** Foundation and appearing in the file LICENSE.GPL included in the
33 ** packaging of this file. Please review the following information to
34 ** ensure the GNU General Public License version 3.0 requirements will be
35 ** met: http://www.gnu.org/copyleft/gpl.html.
40 ****************************************************************************/
43 #include "qbitarray.h"
44 #include "qbytearray.h"
45 #include "qdatastream.h"
48 #include "qdatetime.h"
49 #include "qeasingcurve.h"
51 #include "qregularexpression.h"
53 #include "qstringlist.h"
57 #ifndef QT_BOOTSTRAPPED
58 #include "qabstractitemmodel.h"
59 #include "qjsonvalue.h"
60 #include "qjsonobject.h"
61 #include "qjsonarray.h"
62 #include "qjsondocument.h"
64 #include "private/qvariant_p.h"
65 #include "qmetatype_p.h"
67 #ifndef QT_NO_GEOM_VARIANT
88 static const QVariant::Handler *Handlers[QModulesPrivate::ModulesCount];
90 const QVariant::Handler *operator[] (const uint typeId) const
92 return Handlers[QModulesPrivate::moduleForType(typeId)];
95 void registerHandler(const QModulesPrivate::Names name, const QVariant::Handler *handler)
97 Handlers[name] = handler;
103 struct CoreTypesFilter {
106 static const bool IsAccepted = QModulesPrivate::QTypeModuleInfo<T>::IsCore && QtMetaTypePrivate::TypeDefinition<T>::IsAvailable;
111 namespace { // annonymous used to hide QVariant handlers
113 static void construct(QVariant::Private *x, const void *copy)
115 QVariantConstructor<CoreTypesFilter> constructor(x, copy);
116 QMetaTypeSwitcher::switcher<void>(constructor, x->type, 0);
119 static void clear(QVariant::Private *d)
121 QVariantDestructor<CoreTypesFilter> cleaner(d);
122 QMetaTypeSwitcher::switcher<void>(cleaner, d->type, 0);
125 static bool isNull(const QVariant::Private *d)
127 QVariantIsNull<CoreTypesFilter> isNull(d);
128 return QMetaTypeSwitcher::switcher<bool>(isNull, d->type, 0);
134 Compares \a a to \a b. The caller guarantees that \a a and \a b
135 are of the same type.
137 static bool compare(const QVariant::Private *a, const QVariant::Private *b)
139 QVariantComparator<CoreTypesFilter> comparator(a, b);
140 return QMetaTypeSwitcher::switcher<bool>(comparator, a->type, 0);
146 static qlonglong qMetaTypeNumber(const QVariant::Private *d)
151 case QMetaType::LongLong:
153 case QMetaType::Char:
154 return qlonglong(d->data.c);
155 case QMetaType::SChar:
156 return qlonglong(d->data.sc);
157 case QMetaType::Short:
158 return qlonglong(d->data.s);
159 case QMetaType::Long:
160 return qlonglong(d->data.l);
161 case QMetaType::Float:
162 return qRound64(d->data.f);
163 case QVariant::Double:
164 return qRound64(d->data.d);
170 static qulonglong qMetaTypeUNumber(const QVariant::Private *d)
175 case QVariant::ULongLong:
177 case QMetaType::UChar:
179 case QMetaType::UShort:
181 case QMetaType::ULong:
188 static qlonglong qConvertToNumber(const QVariant::Private *d, bool *ok)
192 switch (uint(d->type)) {
193 case QVariant::String:
194 return v_cast<QString>(d)->toLongLong(ok);
196 return v_cast<QChar>(d)->unicode();
197 case QVariant::ByteArray:
198 return v_cast<QByteArray>(d)->toLongLong(ok);
200 return qlonglong(d->data.b);
201 case QVariant::Double:
203 case QMetaType::Char:
204 case QMetaType::SChar:
205 case QMetaType::Short:
206 case QMetaType::Long:
207 case QMetaType::Float:
208 case QMetaType::LongLong:
209 return qMetaTypeNumber(d);
210 case QVariant::ULongLong:
212 case QMetaType::UChar:
213 case QMetaType::UShort:
214 case QMetaType::ULong:
215 return qlonglong(qMetaTypeUNumber(d));
222 static qulonglong qConvertToUnsignedNumber(const QVariant::Private *d, bool *ok)
226 switch (uint(d->type)) {
227 case QVariant::String:
228 return v_cast<QString>(d)->toULongLong(ok);
230 return v_cast<QChar>(d)->unicode();
231 case QVariant::ByteArray:
232 return v_cast<QByteArray>(d)->toULongLong(ok);
234 return qulonglong(d->data.b);
235 case QVariant::Double:
237 case QMetaType::Char:
238 case QMetaType::SChar:
239 case QMetaType::Short:
240 case QMetaType::Long:
241 case QMetaType::Float:
242 case QMetaType::LongLong:
243 return qulonglong(qMetaTypeNumber(d));
244 case QVariant::ULongLong:
246 case QMetaType::UChar:
247 case QMetaType::UShort:
248 case QMetaType::ULong:
249 return qMetaTypeUNumber(d);
253 return Q_UINT64_C(0);
256 template<typename TInput, typename LiteralWrapper>
257 inline bool qt_convertToBool(const QVariant::Private *const d)
259 TInput str = v_cast<TInput>(d)->toLower();
260 return !(str == LiteralWrapper("0") || str == LiteralWrapper("false") || str.isEmpty());
266 Converts \a d to type \a t, which is placed in \a result.
268 static bool convert(const QVariant::Private *d, int t, void *result, bool *ok)
270 Q_ASSERT(d->type != uint(t));
278 #ifndef QT_BOOTSTRAPPED
281 case QVariant::String:
282 *static_cast<QUrl *>(result) = QUrl(*v_cast<QString>(d));
289 case QVariant::String: {
290 QString *str = static_cast<QString *>(result);
293 *str = QString(*v_cast<QChar>(d));
295 case QMetaType::Char:
296 case QMetaType::SChar:
297 case QMetaType::UChar:
298 *str = QChar::fromLatin1(d->data.c);
300 case QMetaType::Short:
301 case QMetaType::Long:
303 case QVariant::LongLong:
304 *str = QString::number(qMetaTypeNumber(d));
307 case QVariant::ULongLong:
308 case QMetaType::UShort:
309 case QMetaType::ULong:
310 *str = QString::number(qMetaTypeUNumber(d));
312 case QMetaType::Float:
313 *str = QString::number(d->data.f, 'g', FLT_DIG);
315 case QVariant::Double:
316 *str = QString::number(d->data.d, 'g', DBL_DIG);
318 #if !defined(QT_NO_DATESTRING)
320 *str = v_cast<QDate>(d)->toString(Qt::ISODate);
323 *str = v_cast<QTime>(d)->toString(Qt::ISODate);
325 case QVariant::DateTime:
326 *str = v_cast<QDateTime>(d)->toString(Qt::ISODate);
330 *str = QLatin1String(d->data.b ? "true" : "false");
332 case QVariant::ByteArray:
333 *str = QString::fromUtf8(v_cast<QByteArray>(d)->constData());
335 case QVariant::StringList:
336 if (v_cast<QStringList>(d)->count() == 1)
337 *str = v_cast<QStringList>(d)->at(0);
339 #ifndef QT_BOOTSTRAPPED
341 *str = v_cast<QUrl>(d)->toString();
345 *str = v_cast<QUuid>(d)->toString();
352 case QVariant::Char: {
353 QChar *c = static_cast<QChar *>(result);
356 case QVariant::LongLong:
357 case QMetaType::Char:
358 case QMetaType::SChar:
359 case QMetaType::Short:
360 case QMetaType::Long:
361 case QMetaType::Float:
362 *c = QChar(ushort(qMetaTypeNumber(d)));
365 case QVariant::ULongLong:
366 case QMetaType::UChar:
367 case QMetaType::UShort:
368 case QMetaType::ULong:
369 *c = QChar(ushort(qMetaTypeUNumber(d)));
376 #ifndef QT_NO_GEOM_VARIANT
377 case QVariant::Size: {
378 QSize *s = static_cast<QSize *>(result);
380 case QVariant::SizeF:
381 *s = v_cast<QSizeF>(d)->toSize();
389 case QVariant::SizeF: {
390 QSizeF *s = static_cast<QSizeF *>(result);
393 *s = QSizeF(*(v_cast<QSize>(d)));
401 case QVariant::Line: {
402 QLine *s = static_cast<QLine *>(result);
404 case QVariant::LineF:
405 *s = v_cast<QLineF>(d)->toLine();
413 case QVariant::LineF: {
414 QLineF *s = static_cast<QLineF *>(result);
417 *s = QLineF(*(v_cast<QLine>(d)));
425 case QVariant::StringList:
426 if (d->type == QVariant::List) {
427 QStringList *slst = static_cast<QStringList *>(result);
428 const QVariantList *list = v_cast<QVariantList >(d);
429 for (int i = 0; i < list->size(); ++i)
430 slst->append(list->at(i).toString());
431 } else if (d->type == QVariant::String) {
432 QStringList *slst = static_cast<QStringList *>(result);
433 *slst = QStringList(*v_cast<QString>(d));
438 case QVariant::Date: {
439 QDate *dt = static_cast<QDate *>(result);
440 if (d->type == QVariant::DateTime)
441 *dt = v_cast<QDateTime>(d)->date();
442 #ifndef QT_NO_DATESTRING
443 else if (d->type == QVariant::String)
444 *dt = QDate::fromString(*v_cast<QString>(d), Qt::ISODate);
449 return dt->isValid();
451 case QVariant::Time: {
452 QTime *t = static_cast<QTime *>(result);
454 case QVariant::DateTime:
455 *t = v_cast<QDateTime>(d)->time();
457 #ifndef QT_NO_DATESTRING
458 case QVariant::String:
459 *t = QTime::fromString(*v_cast<QString>(d), Qt::ISODate);
467 case QVariant::DateTime: {
468 QDateTime *dt = static_cast<QDateTime *>(result);
470 #ifndef QT_NO_DATESTRING
471 case QVariant::String:
472 *dt = QDateTime::fromString(*v_cast<QString>(d), Qt::ISODate);
476 *dt = QDateTime(*v_cast<QDate>(d));
481 return dt->isValid();
483 case QVariant::ByteArray: {
484 QByteArray *ba = static_cast<QByteArray *>(result);
486 case QVariant::String:
487 *ba = v_cast<QString>(d)->toUtf8();
489 case QVariant::Double:
490 *ba = QByteArray::number(d->data.d, 'g', DBL_DIG);
492 case QMetaType::Float:
493 *ba = QByteArray::number(d->data.f, 'g', FLT_DIG);
495 case QMetaType::Char:
496 case QMetaType::SChar:
497 case QMetaType::UChar:
498 *ba = QByteArray(1, d->data.c);
501 case QVariant::LongLong:
502 case QMetaType::Short:
503 case QMetaType::Long:
504 *ba = QByteArray::number(qMetaTypeNumber(d));
507 case QVariant::ULongLong:
508 case QMetaType::UShort:
509 case QMetaType::ULong:
510 *ba = QByteArray::number(qMetaTypeUNumber(d));
513 *ba = QByteArray(d->data.b ? "true" : "false");
520 case QMetaType::Short:
521 *static_cast<short *>(result) = short(qConvertToNumber(d, ok));
523 case QMetaType::Long:
524 *static_cast<long *>(result) = long(qConvertToNumber(d, ok));
526 case QMetaType::UShort:
527 *static_cast<ushort *>(result) = ushort(qConvertToUnsignedNumber(d, ok));
529 case QMetaType::ULong:
530 *static_cast<ulong *>(result) = ulong(qConvertToUnsignedNumber(d, ok));
533 *static_cast<int *>(result) = int(qConvertToNumber(d, ok));
536 *static_cast<uint *>(result) = uint(qConvertToUnsignedNumber(d, ok));
538 case QVariant::LongLong:
539 *static_cast<qlonglong *>(result) = qConvertToNumber(d, ok);
541 case QVariant::ULongLong: {
542 *static_cast<qulonglong *>(result) = qConvertToUnsignedNumber(d, ok);
545 case QMetaType::SChar: {
546 signed char s = qConvertToNumber(d, ok);
547 *static_cast<signed char*>(result) = s;
550 case QMetaType::UChar: {
551 *static_cast<uchar *>(result) = qConvertToUnsignedNumber(d, ok);
554 case QVariant::Bool: {
555 bool *b = static_cast<bool *>(result);
557 case QVariant::ByteArray:
558 *b = qt_convertToBool<QByteArray, QByteArray>(d);
560 case QVariant::String:
561 *b = qt_convertToBool<QString, QLatin1String>(d);
564 *b = !v_cast<QChar>(d)->isNull();
566 case QVariant::Double:
568 case QVariant::LongLong:
569 case QMetaType::Char:
570 case QMetaType::SChar:
571 case QMetaType::Short:
572 case QMetaType::Long:
573 case QMetaType::Float:
574 *b = qMetaTypeNumber(d) != Q_INT64_C(0);
577 case QVariant::ULongLong:
578 case QMetaType::UChar:
579 case QMetaType::UShort:
580 case QMetaType::ULong:
581 *b = qMetaTypeUNumber(d) != Q_UINT64_C(0);
589 case QVariant::Double: {
590 double *f = static_cast<double *>(result);
592 case QVariant::String:
593 *f = v_cast<QString>(d)->toDouble(ok);
595 case QVariant::ByteArray:
596 *f = v_cast<QByteArray>(d)->toDouble(ok);
599 *f = double(d->data.b);
601 case QMetaType::Float:
602 *f = double(d->data.f);
604 case QVariant::LongLong:
606 case QMetaType::Char:
607 case QMetaType::SChar:
608 case QMetaType::Short:
609 case QMetaType::Long:
610 *f = double(qMetaTypeNumber(d));
613 case QVariant::ULongLong:
614 case QMetaType::UChar:
615 case QMetaType::UShort:
616 case QMetaType::ULong:
617 *f = double(qMetaTypeUNumber(d));
625 case QMetaType::Float: {
626 float *f = static_cast<float *>(result);
628 case QVariant::String:
629 *f = v_cast<QString>(d)->toFloat(ok);
631 case QVariant::ByteArray:
632 *f = v_cast<QByteArray>(d)->toFloat(ok);
635 *f = float(d->data.b);
637 case QVariant::Double:
638 *f = float(d->data.d);
640 case QVariant::LongLong:
642 case QMetaType::Char:
643 case QMetaType::SChar:
644 case QMetaType::Short:
645 case QMetaType::Long:
646 *f = float(qMetaTypeNumber(d));
649 case QVariant::ULongLong:
650 case QMetaType::UChar:
651 case QMetaType::UShort:
652 case QMetaType::ULong:
653 *f = float(qMetaTypeUNumber(d));
662 if (d->type == QVariant::StringList) {
663 QVariantList *lst = static_cast<QVariantList *>(result);
664 const QStringList *slist = v_cast<QStringList>(d);
665 for (int i = 0; i < slist->size(); ++i)
666 lst->append(QVariant(slist->at(i)));
667 } else if (qstrcmp(QMetaType::typeName(d->type), "QList<QVariant>") == 0) {
668 *static_cast<QVariantList *>(result) =
669 *static_cast<QList<QVariant> *>(d->data.shared->ptr);
675 if (qstrcmp(QMetaType::typeName(d->type), "QMap<QString, QVariant>") == 0) {
676 *static_cast<QVariantMap *>(result) =
677 *static_cast<QMap<QString, QVariant> *>(d->data.shared->ptr);
683 if (qstrcmp(QMetaType::typeName(d->type), "QHash<QString, QVariant>") == 0) {
684 *static_cast<QVariantHash *>(result) =
685 *static_cast<QHash<QString, QVariant> *>(d->data.shared->ptr);
690 #ifndef QT_NO_GEOM_VARIANT
692 if (d->type == QVariant::RectF)
693 *static_cast<QRect *>(result) = (v_cast<QRectF>(d))->toRect();
697 case QVariant::RectF:
698 if (d->type == QVariant::Rect)
699 *static_cast<QRectF *>(result) = *v_cast<QRect>(d);
703 case QVariant::PointF:
704 if (d->type == QVariant::Point)
705 *static_cast<QPointF *>(result) = *v_cast<QPoint>(d);
709 case QVariant::Point:
710 if (d->type == QVariant::PointF)
711 *static_cast<QPoint *>(result) = (v_cast<QPointF>(d))->toPoint();
715 case QMetaType::Char:
717 *static_cast<qint8 *>(result) = qint8(qConvertToNumber(d, ok));
723 case QVariant::String:
724 *static_cast<QUuid *>(result) = QUuid(*v_cast<QString>(d));
736 #if !defined(QT_NO_DEBUG_STREAM)
737 static void streamDebug(QDebug dbg, const QVariant &v)
739 QVariant::Private *d = const_cast<QVariant::Private *>(&v.data_ptr());
740 QVariantDebugStream<CoreTypesFilter> stream(dbg, d);
741 QMetaTypeSwitcher::switcher<void>(stream, d->type, 0);
745 const QVariant::Handler qt_kernel_variant_handler = {
749 #ifndef QT_NO_DATASTREAM
756 #if !defined(QT_NO_DEBUG_STREAM)
763 static void dummyConstruct(QVariant::Private *, const void *) { Q_ASSERT_X(false, "QVariant", "Trying to construct an unknown type"); }
764 static void dummyClear(QVariant::Private *) { Q_ASSERT_X(false, "QVariant", "Trying to clear an unknown type"); }
765 static bool dummyIsNull(const QVariant::Private *d) { Q_ASSERT_X(false, "QVariant::isNull", "Trying to call isNull on an unknown type"); return d->is_null; }
766 static bool dummyCompare(const QVariant::Private *, const QVariant::Private *) { Q_ASSERT_X(false, "QVariant", "Trying to compare an unknown types"); return false; }
767 static bool dummyConvert(const QVariant::Private *, int, void *, bool *) { Q_ASSERT_X(false, "QVariant", "Trying to convert an unknown type"); return false; }
768 #if !defined(QT_NO_DEBUG_STREAM)
769 static void dummyStreamDebug(QDebug, const QVariant &) { Q_ASSERT_X(false, "QVariant", "Trying to convert an unknown type"); }
771 const QVariant::Handler qt_dummy_variant_handler = {
775 #ifndef QT_NO_DATASTREAM
782 #if !defined(QT_NO_DEBUG_STREAM)
789 static void customConstruct(QVariant::Private *d, const void *copy)
791 const QMetaType type(d->type);
792 const uint size = type.sizeOf();
794 qWarning("Trying to construct an instance of an invalid type, type id: %i", d->type);
795 d->type = QVariant::Invalid;
799 // this logic should match with QVariantIntegrator::CanUseInternalSpace
800 if (size <= sizeof(QVariant::Private::Data)
801 && (type.flags() & QMetaType::MovableType)) {
802 type.construct(&d->data.ptr, copy);
803 d->is_shared = false;
805 void *ptr = type.create(copy);
807 d->data.shared = new QVariant::PrivateShared(ptr);
811 static void customClear(QVariant::Private *d)
814 QMetaType::destruct(d->type, &d->data.ptr);
816 QMetaType::destroy(d->type, d->data.shared->ptr);
817 delete d->data.shared;
821 static bool customIsNull(const QVariant::Private *d)
826 static bool customCompare(const QVariant::Private *a, const QVariant::Private *b)
828 const char *const typeName = QMetaType::typeName(a->type);
829 if (Q_UNLIKELY(!typeName) && Q_LIKELY(!QMetaType::isRegistered(a->type)))
830 qFatal("QVariant::compare: type %d unknown to QVariant.", a->type);
832 const void *a_ptr = a->is_shared ? a->data.shared->ptr : &(a->data.ptr);
833 const void *b_ptr = b->is_shared ? b->data.shared->ptr : &(b->data.ptr);
835 uint typeNameLen = qstrlen(typeName);
836 if (typeNameLen > 0 && typeName[typeNameLen - 1] == '*')
837 return *static_cast<void *const *>(a_ptr) == *static_cast<void *const *>(b_ptr);
839 if (a->is_null && b->is_null)
842 return !memcmp(a_ptr, b_ptr, QMetaType::sizeOf(a->type));
845 static bool customConvert(const QVariant::Private *, int, void *, bool *ok)
852 #if !defined(QT_NO_DEBUG_STREAM)
853 static void customStreamDebug(QDebug dbg, const QVariant &variant) {
854 #ifndef QT_BOOTSTRAPPED
855 QMetaType::TypeFlags flags = QMetaType::typeFlags(variant.userType());
856 if (flags & QMetaType::PointerToQObject)
857 dbg.nospace() << variant.value<QObject*>();
865 const QVariant::Handler qt_custom_variant_handler = {
869 #ifndef QT_NO_DATASTREAM
876 #if !defined(QT_NO_DEBUG_STREAM)
883 } // annonymous used to hide QVariant handlers
885 static HandlersManager handlerManager;
886 Q_STATIC_ASSERT_X(!QModulesPrivate::Core, "Initialization assumes that ModulesNames::Core is 0");
887 const QVariant::Handler *HandlersManager::Handlers[QModulesPrivate::ModulesCount]
888 = { &qt_kernel_variant_handler, &qt_dummy_variant_handler,
889 &qt_dummy_variant_handler, &qt_custom_variant_handler };
891 Q_CORE_EXPORT const QVariant::Handler *qcoreVariantHandler()
893 return &qt_kernel_variant_handler;
896 Q_CORE_EXPORT void QVariantPrivate::registerHandler(const int /* Modules::Names */name, const QVariant::Handler *handler)
898 handlerManager.registerHandler(static_cast<QModulesPrivate::Names>(name), handler);
904 \brief The QVariant class acts like a union for the most common Qt data types.
910 Because C++ forbids unions from including types that have
911 non-default constructors or destructors, most interesting Qt
912 classes cannot be used in unions. Without QVariant, this would be
913 a problem for QObject::property() and for database work, etc.
915 A QVariant object holds a single value of a single type() at a
916 time. (Some type()s are multi-valued, for example a string list.)
917 You can find out what type, T, the variant holds, convert it to a
918 different type using convert(), get its value using one of the
919 toT() functions (e.g., toSize()) and check whether the type can
920 be converted to a particular type using canConvert().
922 The methods named toT() (e.g., toInt(), toString()) are const. If
923 you ask for the stored type, they return a copy of the stored
924 object. If you ask for a type that can be generated from the
925 stored type, toT() copies and converts and leaves the object
926 itself unchanged. If you ask for a type that cannot be generated
927 from the stored type, the result depends on the type; see the
928 function documentation for details.
930 Here is some example code to demonstrate the use of QVariant:
932 \snippet code/src_corelib_kernel_qvariant.cpp 0
934 You can even store QList<QVariant> and QMap<QString, QVariant>
935 values in a variant, so you can easily construct arbitrarily
936 complex data structures of arbitrary types. This is very powerful
937 and versatile, but may prove less memory and speed efficient than
938 storing specific types in standard data structures.
940 QVariant also supports the notion of null values, where you can
941 have a defined type with no value set. However, note that QVariant
942 types can only be cast when they have had a value set.
944 \snippet code/src_corelib_kernel_qvariant.cpp 1
946 QVariant can be extended to support other types than those
947 mentioned in the \l Type enum. See the \l QMetaType documentation
950 \section1 A Note on GUI Types
952 Because QVariant is part of the QtCore library, it cannot provide
953 conversion functions to data types defined in QtGui, such as
954 QColor, QImage, and QPixmap. In other words, there is no \c
955 toColor() function. Instead, you can use the QVariant::value() or
956 the qvariant_cast() template function. For example:
958 \snippet code/src_corelib_kernel_qvariant.cpp 2
960 The inverse conversion (e.g., from QColor to QVariant) is
961 automatic for all data types supported by QVariant, including
964 \snippet code/src_corelib_kernel_qvariant.cpp 3
966 \section1 Using canConvert() and convert() Consecutively
968 When using canConvert() and convert() consecutively, it is possible for
969 canConvert() to return true, but convert() to return false. This
970 is typically because canConvert() only reports the general ability of
971 QVariant to convert between types given suitable data; it is still
972 possible to supply data which cannot actually be converted.
974 For example, canConvert() would return true when called on a variant
975 containing a string because, in principle, QVariant is able to convert
976 strings of numbers to integers.
977 However, if the string contains non-numeric characters, it cannot be
978 converted to an integer, and any attempt to convert it will fail.
979 Hence, it is important to have both functions return true for a
980 successful conversion.
986 \obsolete Use QMetaType::Type instead
989 This enum type defines the types of variable that a QVariant can
992 \value Invalid no type
993 \value BitArray a QBitArray
994 \value Bitmap a QBitmap
996 \value Brush a QBrush
997 \value ByteArray a QByteArray
999 \value Color a QColor
1000 \value Cursor a QCursor
1002 \value DateTime a QDateTime
1003 \value Double a double
1004 \value EasingCurve a QEasingCurve
1006 \value ModelIndex a QModelIndex
1008 \value Hash a QVariantHash
1010 \value Image a QImage
1012 \value KeySequence a QKeySequence
1014 \value LineF a QLineF
1015 \value List a QVariantList
1016 \value Locale a QLocale
1017 \value LongLong a \l qlonglong
1018 \value Map a QVariantMap
1019 \value Matrix a QMatrix
1020 \value Transform a QTransform
1021 \value Matrix4x4 a QMatrix4x4
1022 \value Palette a QPalette
1024 \value Pixmap a QPixmap
1025 \value Point a QPoint
1026 \value PointF a QPointF
1027 \value Polygon a QPolygon
1028 \value PolygonF a QPolygonF
1029 \value Quaternion a QQuaternion
1031 \value RectF a QRectF
1032 \value RegExp a QRegExp
1033 \value RegularExpression a QRegularExpression
1034 \value Region a QRegion
1036 \value SizeF a QSizeF
1037 \value SizePolicy a QSizePolicy
1038 \value String a QString
1039 \value StringList a QStringList
1040 \value TextFormat a QTextFormat
1041 \value TextLength a QTextLength
1043 \value UInt a \l uint
1044 \value ULongLong a \l qulonglong
1046 \value Vector2D a QVector2D
1047 \value Vector3D a QVector3D
1048 \value Vector4D a QVector4D
1050 \value UserType Base value for user-defined types.
1052 \omitvalue LastGuiType
1053 \omitvalue LastCoreType
1058 \fn QVariant::QVariant()
1060 Constructs an invalid variant.
1065 \fn QVariant::QVariant(int typeId, const void *copy)
1067 Constructs variant of type \a typeId, and initializes with
1068 \a copy if \a copy is not 0.
1070 Note that you have to pass the address of the variable you want stored.
1072 Usually, you never have to use this constructor, use QVariant::fromValue()
1073 instead to construct variants from the pointer types represented by
1074 \c QMetaType::VoidStar, and \c QMetaType::QObjectStar.
1076 \sa QVariant::fromValue(), Type
1080 \fn QVariant::QVariant(Type type)
1082 Constructs a null variant of type \a type.
1088 \fn QVariant::create(int type, const void *copy)
1092 Constructs a variant private of type \a type, and initializes with \a copy if
1096 void QVariant::create(int type, const void *copy)
1099 handlerManager[type]->construct(&d, copy);
1103 \fn QVariant::~QVariant()
1105 Destroys the QVariant and the contained object.
1107 Note that subclasses that reimplement clear() should reimplement
1108 the destructor to call clear(). This destructor calls clear(), but
1109 because it is the destructor, QVariant::clear() is called rather
1110 than a subclass's clear().
1113 QVariant::~QVariant()
1115 if ((d.is_shared && !d.data.shared->ref.deref()) || (!d.is_shared && d.type > Char))
1116 handlerManager[d.type]->clear(&d);
1120 \fn QVariant::QVariant(const QVariant &p)
1122 Constructs a copy of the variant, \a p, passed as the argument to
1126 QVariant::QVariant(const QVariant &p)
1130 d.data.shared->ref.ref();
1131 } else if (p.d.type > Char) {
1132 handlerManager[d.type]->construct(&d, p.constData());
1133 d.is_null = p.d.is_null;
1137 #ifndef QT_NO_DATASTREAM
1139 Reads the variant from the data stream, \a s.
1141 QVariant::QVariant(QDataStream &s)
1146 #endif //QT_NO_DATASTREAM
1149 \fn QVariant::QVariant(const QString &val)
1151 Constructs a new variant with a string value, \a val.
1155 \fn QVariant::QVariant(QLatin1String val)
1157 Constructs a new variant with a string value, \a val.
1161 \fn QVariant::QVariant(const char *val)
1163 Constructs a new variant with a string value of \a val.
1164 The variant creates a deep copy of \a val into a QString assuming
1165 UTF-8 encoding on the input \a val.
1167 Note that \a val is converted to a QString for storing in the
1168 variant and QVariant::userType() will return QMetaType::QString for
1171 You can disable this operator by defining \c
1172 QT_NO_CAST_FROM_ASCII when you compile your applications.
1175 #ifndef QT_NO_CAST_FROM_ASCII
1176 QVariant::QVariant(const char *val)
1178 QString s = QString::fromUtf8(val);
1184 \fn QVariant::QVariant(const QStringList &val)
1186 Constructs a new variant with a string list value, \a val.
1190 \fn QVariant::QVariant(const QMap<QString, QVariant> &val)
1192 Constructs a new variant with a map of QVariants, \a val.
1196 \fn QVariant::QVariant(const QHash<QString, QVariant> &val)
1198 Constructs a new variant with a hash of QVariants, \a val.
1202 \fn QVariant::QVariant(const QDate &val)
1204 Constructs a new variant with a date value, \a val.
1208 \fn QVariant::QVariant(const QTime &val)
1210 Constructs a new variant with a time value, \a val.
1214 \fn QVariant::QVariant(const QDateTime &val)
1216 Constructs a new variant with a date/time value, \a val.
1221 \fn QVariant::QVariant(const QEasingCurve &val)
1223 Constructs a new variant with an easing curve value, \a val.
1228 \fn QVariant::QVariant(const QUuid &val)
1230 Constructs a new variant with an uuid value, \a val.
1235 \fn QVariant::QVariant(const QModelIndex &val)
1237 Constructs a new variant with an modelIndex value, \a val.
1242 \fn QVariant::QVariant(const QJsonValue &val)
1244 Constructs a new variant with a json value, \a val.
1249 \fn QVariant::QVariant(const QJsonObject &val)
1251 Constructs a new variant with a json object value, \a val.
1256 \fn QVariant::QVariant(const QJsonArray &val)
1258 Constructs a new variant with a json array value, \a val.
1263 \fn QVariant::QVariant(const QJsonDocument &val)
1265 Constructs a new variant with a json document value, \a val.
1269 \fn QVariant::QVariant(const QByteArray &val)
1271 Constructs a new variant with a bytearray value, \a val.
1275 \fn QVariant::QVariant(const QBitArray &val)
1277 Constructs a new variant with a bitarray value, \a val.
1281 \fn QVariant::QVariant(const QPoint &val)
1283 Constructs a new variant with a point value of \a val.
1287 \fn QVariant::QVariant(const QPointF &val)
1289 Constructs a new variant with a point value of \a val.
1293 \fn QVariant::QVariant(const QRectF &val)
1295 Constructs a new variant with a rect value of \a val.
1299 \fn QVariant::QVariant(const QLineF &val)
1301 Constructs a new variant with a line value of \a val.
1305 \fn QVariant::QVariant(const QLine &val)
1307 Constructs a new variant with a line value of \a val.
1311 \fn QVariant::QVariant(const QRect &val)
1313 Constructs a new variant with a rect value of \a val.
1317 \fn QVariant::QVariant(const QSize &val)
1319 Constructs a new variant with a size value of \a val.
1323 \fn QVariant::QVariant(const QSizeF &val)
1325 Constructs a new variant with a size value of \a val.
1329 \fn QVariant::QVariant(const QUrl &val)
1331 Constructs a new variant with a url value of \a val.
1335 \fn QVariant::QVariant(int val)
1337 Constructs a new variant with an integer value, \a val.
1341 \fn QVariant::QVariant(uint val)
1343 Constructs a new variant with an unsigned integer value, \a val.
1347 \fn QVariant::QVariant(qlonglong val)
1349 Constructs a new variant with a long long integer value, \a val.
1353 \fn QVariant::QVariant(qulonglong val)
1355 Constructs a new variant with an unsigned long long integer value, \a val.
1360 \fn QVariant::QVariant(bool val)
1362 Constructs a new variant with a boolean value, \a val.
1366 \fn QVariant::QVariant(double val)
1368 Constructs a new variant with a floating point value, \a val.
1372 \fn QVariant::QVariant(float val)
1374 Constructs a new variant with a floating point value, \a val.
1379 \fn QVariant::QVariant(const QList<QVariant> &val)
1381 Constructs a new variant with a list value, \a val.
1385 \fn QVariant::QVariant(QChar c)
1387 Constructs a new variant with a char value, \a c.
1391 \fn QVariant::QVariant(const QLocale &l)
1393 Constructs a new variant with a locale value, \a l.
1397 \fn QVariant::QVariant(const QRegExp ®Exp)
1399 Constructs a new variant with the regexp value \a regExp.
1403 \fn QVariant::QVariant(const QRegularExpression &re)
1407 Constructs a new variant with the regular expression value \a re.
1410 QVariant::QVariant(Type type)
1411 { create(type, 0); }
1412 QVariant::QVariant(int typeId, const void *copy)
1413 { create(typeId, copy); d.is_null = false; }
1417 flags is true if it is a pointer type
1419 QVariant::QVariant(int typeId, const void *copy, uint flags)
1421 if (flags) { //type is a pointer type
1423 d.data.ptr = *reinterpret_cast<void *const*>(copy);
1425 create(typeId, copy);
1430 QVariant::QVariant(int val)
1433 QVariant::QVariant(uint val)
1436 QVariant::QVariant(qlonglong val)
1438 { d.data.ll = val; }
1439 QVariant::QVariant(qulonglong val)
1441 { d.data.ull = val; }
1442 QVariant::QVariant(bool val)
1445 QVariant::QVariant(double val)
1448 QVariant::QVariant(float val)
1449 : d(QMetaType::Float)
1452 QVariant::QVariant(const QByteArray &val)
1454 { v_construct<QByteArray>(&d, val); }
1455 QVariant::QVariant(const QBitArray &val)
1457 { v_construct<QBitArray>(&d, val); }
1458 QVariant::QVariant(const QString &val)
1460 { v_construct<QString>(&d, val); }
1461 QVariant::QVariant(QChar val)
1463 { v_construct<QChar>(&d, val); }
1464 QVariant::QVariant(QLatin1String val)
1466 { v_construct<QString>(&d, val); }
1467 QVariant::QVariant(const QStringList &val)
1469 { v_construct<QStringList>(&d, val); }
1471 QVariant::QVariant(const QDate &val)
1473 { v_construct<QDate>(&d, val); }
1474 QVariant::QVariant(const QTime &val)
1476 { v_construct<QTime>(&d, val); }
1477 QVariant::QVariant(const QDateTime &val)
1479 { v_construct<QDateTime>(&d, val); }
1480 #ifndef QT_BOOTSTRAPPED
1481 QVariant::QVariant(const QEasingCurve &val)
1483 { v_construct<QEasingCurve>(&d, val); }
1485 QVariant::QVariant(const QList<QVariant> &list)
1487 { v_construct<QVariantList>(&d, list); }
1488 QVariant::QVariant(const QMap<QString, QVariant> &map)
1490 { v_construct<QVariantMap>(&d, map); }
1491 QVariant::QVariant(const QHash<QString, QVariant> &hash)
1493 { v_construct<QVariantHash>(&d, hash); }
1494 #ifndef QT_NO_GEOM_VARIANT
1495 QVariant::QVariant(const QPoint &pt)
1497 { v_construct<QPoint>(&d, pt); }
1498 QVariant::QVariant(const QPointF &pt)
1500 { v_construct<QPointF>(&d, pt); }
1501 QVariant::QVariant(const QRectF &r)
1503 { v_construct<QRectF>(&d, r); }
1504 QVariant::QVariant(const QLineF &l)
1506 { v_construct<QLineF>(&d, l); }
1507 QVariant::QVariant(const QLine &l)
1509 { v_construct<QLine>(&d, l); }
1510 QVariant::QVariant(const QRect &r)
1512 { v_construct<QRect>(&d, r); }
1513 QVariant::QVariant(const QSize &s)
1515 { v_construct<QSize>(&d, s); }
1516 QVariant::QVariant(const QSizeF &s)
1518 { v_construct<QSizeF>(&d, s); }
1520 #ifndef QT_BOOTSTRAPPED
1521 QVariant::QVariant(const QUrl &u)
1523 { v_construct<QUrl>(&d, u); }
1525 QVariant::QVariant(const QLocale &l)
1527 { v_construct<QLocale>(&d, l); }
1528 #ifndef QT_NO_REGEXP
1529 QVariant::QVariant(const QRegExp ®Exp)
1531 { v_construct<QRegExp>(&d, regExp); }
1532 #ifndef QT_BOOTSTRAPPED
1533 QVariant::QVariant(const QRegularExpression &re)
1534 : d(RegularExpression)
1535 { v_construct<QRegularExpression>(&d, re); }
1536 QVariant::QVariant(const QUuid &uuid)
1538 { v_construct<QUuid>(&d, uuid); }
1539 QVariant::QVariant(const QModelIndex &modelIndex)
1541 { v_construct<QModelIndex>(&d, modelIndex); }
1542 QVariant::QVariant(const QJsonValue &jsonValue)
1543 : d(QMetaType::QJsonValue)
1544 { v_construct<QJsonValue>(&d, jsonValue); }
1545 QVariant::QVariant(const QJsonObject &jsonObject)
1546 : d(QMetaType::QJsonObject)
1547 { v_construct<QJsonObject>(&d, jsonObject); }
1548 QVariant::QVariant(const QJsonArray &jsonArray)
1549 : d(QMetaType::QJsonArray)
1550 { v_construct<QJsonArray>(&d, jsonArray); }
1551 QVariant::QVariant(const QJsonDocument &jsonDocument)
1552 : d(QMetaType::QJsonDocument)
1553 { v_construct<QJsonDocument>(&d, jsonDocument); }
1554 #endif // QT_BOOTSTRAPPED
1555 #endif // QT_NO_REGEXP
1558 Returns the storage type of the value stored in the variant.
1559 Although this function is declared as returning QVariant::Type,
1560 the return value should be interpreted as QMetaType::Type. In
1561 particular, QVariant::UserType is returned here only if the value
1562 is equal or greater than QMetaType::User.
1564 Note that return values in the ranges QVariant::Char through
1565 QVariant::RegExp and QVariant::Font through QVariant::Transform
1566 correspond to the values in the ranges QMetaType::QChar through
1567 QMetaType::QRegExp and QMetaType::QFont through QMetaType::QQuaternion.
1569 Pay particular attention when working with char and QChar
1570 variants. Note that there is no QVariant constructor specifically
1571 for type char, but there is one for QChar. For a variant of type
1572 QChar, this function returns QVariant::Char, which is the same as
1573 QMetaType::QChar, but for a variant of type \c char, this function
1574 returns QMetaType::Char, which is \e not the same as
1577 Also note that the types \c void*, \c long, \c short, \c unsigned
1578 \c long, \c unsigned \c short, \c unsigned \c char, \c float, \c
1579 QObject*, and \c QWidget* are represented in QMetaType::Type but
1580 not in QVariant::Type, and they can be returned by this function.
1581 However, they are considered to be user defined types when tested
1582 against QVariant::Type.
1584 To test whether an instance of QVariant contains a data type that
1585 is compatible with the data type you are interested in, use
1589 QVariant::Type QVariant::type() const
1591 return d.type >= QMetaType::User ? UserType : static_cast<Type>(d.type);
1595 Returns the storage type of the value stored in the variant. For
1596 non-user types, this is the same as type().
1601 int QVariant::userType() const
1607 Assigns the value of the variant \a variant to this variant.
1609 QVariant& QVariant::operator=(const QVariant &variant)
1611 if (this == &variant)
1615 if (variant.d.is_shared) {
1616 variant.d.data.shared->ref.ref();
1618 } else if (variant.d.type > Char) {
1619 d.type = variant.d.type;
1620 handlerManager[d.type]->construct(&d, variant.constData());
1621 d.is_null = variant.d.is_null;
1630 \fn void QVariant::swap(QVariant &other)
1633 Swaps variant \a other with this variant. This operation is very
1634 fast and never fails.
1638 \fn void QVariant::detach()
1643 void QVariant::detach()
1645 if (!d.is_shared || d.data.shared->ref.load() == 1)
1650 handlerManager[d.type]->construct(&dd, constData());
1651 if (!d.data.shared->ref.deref())
1652 handlerManager[d.type]->clear(&d);
1653 d.data.shared = dd.data.shared;
1657 \fn bool QVariant::isDetached() const
1663 Returns the name of the type stored in the variant. The returned
1664 strings describe the C++ datatype used to store the data: for
1665 example, "QFont", "QString", or "QVariantList". An Invalid
1668 const char *QVariant::typeName() const
1670 return QMetaType::typeName(d.type);
1674 Convert this variant to type Invalid and free up any resources
1677 void QVariant::clear()
1679 if ((d.is_shared && !d.data.shared->ref.deref()) || (!d.is_shared && d.type > Char))
1680 handlerManager[d.type]->clear(&d);
1683 d.is_shared = false;
1687 Converts the int representation of the storage type, \a typeId, to
1688 its string representation.
1690 Returns a null pointer if the type is QVariant::Invalid or doesn't exist.
1692 const char *QVariant::typeToName(int typeId)
1694 return QMetaType::typeName(typeId);
1699 Converts the string representation of the storage type given in \a
1700 name, to its enum representation.
1702 If the string representation cannot be converted to any enum
1703 representation, the variant is set to \c Invalid.
1705 QVariant::Type QVariant::nameToType(const char *name)
1707 int metaType = QMetaType::type(name);
1708 return metaType <= int(UserType) ? QVariant::Type(metaType) : UserType;
1711 #ifndef QT_NO_DATASTREAM
1712 enum { MapFromThreeCount = 36 };
1713 static const ushort mapIdFromQt3ToCurrent[MapFromThreeCount] =
1719 QVariant::StringList,
1735 0, // Buggy ByteArray, QByteArray never had id == 20
1740 QVariant::SizePolicy,
1744 QVariant::ByteArray,
1746 QVariant::KeySequence,
1749 QVariant::ULongLong,
1750 QVariant::EasingCurve
1754 Internal function for loading a variant from stream \a s. Use the
1755 stream operators instead.
1759 void QVariant::load(QDataStream &s)
1765 if (s.version() < QDataStream::Qt_4_0) {
1766 if (typeId >= MapFromThreeCount)
1768 typeId = mapIdFromQt3ToCurrent[typeId];
1769 } else if (s.version() < QDataStream::Qt_5_0) {
1770 if (typeId == 127 /* QVariant::UserType */) {
1771 typeId = QMetaType::User;
1772 } else if (typeId >= 128 && typeId != QVariant::UserType) {
1773 // In Qt4 id == 128 was FirstExtCoreType. In Qt5 ExtCoreTypes set was merged to CoreTypes
1774 // by moving all ids down by 97.
1776 } else if (typeId == 75 /* QSizePolicy */) {
1777 typeId = QMetaType::QSizePolicy;
1778 } else if (typeId > 75 && typeId <= 86) {
1779 // and as a result these types received lower ids too
1780 // QKeySequence QPen QTextLength QTextFormat QMatrix QTransform QMatrix4x4 QVector2D QVector3D QVector4D QQuaternion
1785 qint8 is_null = false;
1786 if (s.version() >= QDataStream::Qt_4_2)
1788 if (typeId == QVariant::UserType) {
1791 typeId = QMetaType::type(name.constData());
1792 if (typeId == QMetaType::UnknownType) {
1793 s.setStatus(QDataStream::ReadCorruptData);
1798 d.is_null = is_null;
1801 if (s.version() < QDataStream::Qt_5_0) {
1802 // Since we wrote something, we should read something
1810 // const cast is safe since we operate on a newly constructed variant
1811 if (!QMetaType::load(s, d.type, const_cast<void *>(constData()))) {
1812 s.setStatus(QDataStream::ReadCorruptData);
1813 qWarning("QVariant::load: unable to load type %d.", d.type);
1818 Internal function for saving a variant to the stream \a s. Use the
1819 stream operators instead.
1823 void QVariant::save(QDataStream &s) const
1825 quint32 typeId = type();
1826 if (s.version() < QDataStream::Qt_4_0) {
1828 for (i = 0; i <= MapFromThreeCount - 1; ++i) {
1829 if (mapIdFromQt3ToCurrent[i] == typeId) {
1834 if (i >= MapFromThreeCount) {
1838 } else if (s.version() < QDataStream::Qt_5_0) {
1839 if (typeId == QMetaType::User) {
1840 typeId = 127; // QVariant::UserType had this value in Qt4
1841 } else if (typeId >= 128 - 97 && typeId <= LastCoreType) {
1842 // In Qt4 id == 128 was FirstExtCoreType. In Qt5 ExtCoreTypes set was merged to CoreTypes
1843 // by moving all ids down by 97.
1845 } else if (typeId == QMetaType::QSizePolicy) {
1847 } else if (typeId >= QMetaType::QKeySequence && typeId <= QMetaType::QQuaternion) {
1848 // and as a result these types received lower ids too
1853 if (s.version() >= QDataStream::Qt_4_2)
1854 s << qint8(d.is_null);
1855 if (d.type >= QVariant::UserType) {
1856 s << QMetaType::typeName(userType());
1860 if (s.version() < QDataStream::Qt_5_0)
1865 if (!QMetaType::save(s, d.type, constData())) {
1866 qWarning("QVariant::save: unable to save type '%s' (type id: %d).\n", QMetaType::typeName(d.type), d.type);
1867 Q_ASSERT_X(false, "QVariant::save", "Invalid type to save");
1874 Reads a variant \a p from the stream \a s.
1876 \sa{Serializing Qt Data Types}{Format of the QDataStream operators}
1878 QDataStream& operator>>(QDataStream &s, QVariant &p)
1885 Writes a variant \a p to the stream \a s.
1887 \sa{Serializing Qt Data Types}{Format of the QDataStream operators}
1889 QDataStream& operator<<(QDataStream &s, const QVariant &p)
1896 Reads a variant type \a p in enum representation from the stream \a s.
1898 QDataStream& operator>>(QDataStream &s, QVariant::Type &p)
1902 p = (QVariant::Type)u;
1908 Writes a variant type \a p to the stream \a s.
1910 QDataStream& operator<<(QDataStream &s, const QVariant::Type p)
1912 s << static_cast<quint32>(p);
1917 #endif //QT_NO_DATASTREAM
1920 \fn bool QVariant::isValid() const
1922 Returns true if the storage type of this variant is not
1923 QVariant::Invalid; otherwise returns false.
1926 template <typename T>
1927 inline T qVariantToHelper(const QVariant::Private &d, const HandlersManager &handlerManager)
1929 const uint targetType = qMetaTypeId<T>();
1930 if (d.type == targetType)
1931 return *v_cast<T>(&d);
1934 handlerManager[d.type]->convert(&d, targetType, &ret, 0);
1939 \fn QStringList QVariant::toStringList() const
1941 Returns the variant as a QStringList if the variant has type()
1942 StringList, \l String, or \l List of a type that can be converted
1943 to QString; otherwise returns an empty list.
1945 \sa canConvert(), convert()
1947 QStringList QVariant::toStringList() const
1949 return qVariantToHelper<QStringList>(d, handlerManager);
1953 Returns the variant as a QString if the variant has type() \l
1954 String, \l Bool, \l ByteArray, \l Char, \l Date, \l DateTime, \l
1955 Double, \l Int, \l LongLong, \l StringList, \l Time, \l UInt, or
1956 \l ULongLong; otherwise returns an empty string.
1958 \sa canConvert(), convert()
1960 QString QVariant::toString() const
1962 return qVariantToHelper<QString>(d, handlerManager);
1966 Returns the variant as a QMap<QString, QVariant> if the variant
1967 has type() \l Map; otherwise returns an empty map.
1969 \sa canConvert(), convert()
1971 QVariantMap QVariant::toMap() const
1973 return qVariantToHelper<QVariantMap>(d, handlerManager);
1977 Returns the variant as a QHash<QString, QVariant> if the variant
1978 has type() \l Hash; otherwise returns an empty map.
1980 \sa canConvert(), convert()
1982 QVariantHash QVariant::toHash() const
1984 return qVariantToHelper<QVariantHash>(d, handlerManager);
1988 \fn QDate QVariant::toDate() const
1990 Returns the variant as a QDate if the variant has type() \l Date,
1991 \l DateTime, or \l String; otherwise returns an invalid date.
1993 If the type() is \l String, an invalid date will be returned if the
1994 string cannot be parsed as a Qt::ISODate format date.
1996 \sa canConvert(), convert()
1998 QDate QVariant::toDate() const
2000 return qVariantToHelper<QDate>(d, handlerManager);
2004 \fn QTime QVariant::toTime() const
2006 Returns the variant as a QTime if the variant has type() \l Time,
2007 \l DateTime, or \l String; otherwise returns an invalid time.
2009 If the type() is \l String, an invalid time will be returned if
2010 the string cannot be parsed as a Qt::ISODate format time.
2012 \sa canConvert(), convert()
2014 QTime QVariant::toTime() const
2016 return qVariantToHelper<QTime>(d, handlerManager);
2020 \fn QDateTime QVariant::toDateTime() const
2022 Returns the variant as a QDateTime if the variant has type() \l
2023 DateTime, \l Date, or \l String; otherwise returns an invalid
2026 If the type() is \l String, an invalid date/time will be returned
2027 if the string cannot be parsed as a Qt::ISODate format date/time.
2029 \sa canConvert(), convert()
2031 QDateTime QVariant::toDateTime() const
2033 return qVariantToHelper<QDateTime>(d, handlerManager);
2038 \fn QEasingCurve QVariant::toEasingCurve() const
2040 Returns the variant as a QEasingCurve if the variant has type() \l
2041 EasingCurve; otherwise returns a default easing curve.
2043 \sa canConvert(), convert()
2045 #ifndef QT_BOOTSTRAPPED
2046 QEasingCurve QVariant::toEasingCurve() const
2048 return qVariantToHelper<QEasingCurve>(d, handlerManager);
2053 \fn QByteArray QVariant::toByteArray() const
2055 Returns the variant as a QByteArray if the variant has type() \l
2056 ByteArray or \l String (converted using QString::fromUtf8());
2057 otherwise returns an empty byte array.
2059 \sa canConvert(), convert()
2061 QByteArray QVariant::toByteArray() const
2063 return qVariantToHelper<QByteArray>(d, handlerManager);
2066 #ifndef QT_NO_GEOM_VARIANT
2068 \fn QPoint QVariant::toPoint() const
2070 Returns the variant as a QPoint if the variant has type()
2071 \l Point or \l PointF; otherwise returns a null QPoint.
2073 \sa canConvert(), convert()
2075 QPoint QVariant::toPoint() const
2077 return qVariantToHelper<QPoint>(d, handlerManager);
2081 \fn QRect QVariant::toRect() const
2083 Returns the variant as a QRect if the variant has type() \l Rect;
2084 otherwise returns an invalid QRect.
2086 \sa canConvert(), convert()
2088 QRect QVariant::toRect() const
2090 return qVariantToHelper<QRect>(d, handlerManager);
2094 \fn QSize QVariant::toSize() const
2096 Returns the variant as a QSize if the variant has type() \l Size;
2097 otherwise returns an invalid QSize.
2099 \sa canConvert(), convert()
2101 QSize QVariant::toSize() const
2103 return qVariantToHelper<QSize>(d, handlerManager);
2107 \fn QSizeF QVariant::toSizeF() const
2109 Returns the variant as a QSizeF if the variant has type() \l
2110 SizeF; otherwise returns an invalid QSizeF.
2112 \sa canConvert(), convert()
2114 QSizeF QVariant::toSizeF() const
2116 return qVariantToHelper<QSizeF>(d, handlerManager);
2120 \fn QRectF QVariant::toRectF() const
2122 Returns the variant as a QRectF if the variant has type() \l Rect
2123 or \l RectF; otherwise returns an invalid QRectF.
2125 \sa canConvert(), convert()
2127 QRectF QVariant::toRectF() const
2129 return qVariantToHelper<QRectF>(d, handlerManager);
2133 \fn QLineF QVariant::toLineF() const
2135 Returns the variant as a QLineF if the variant has type() \l
2136 LineF; otherwise returns an invalid QLineF.
2138 \sa canConvert(), convert()
2140 QLineF QVariant::toLineF() const
2142 return qVariantToHelper<QLineF>(d, handlerManager);
2146 \fn QLine QVariant::toLine() const
2148 Returns the variant as a QLine if the variant has type() \l Line;
2149 otherwise returns an invalid QLine.
2151 \sa canConvert(), convert()
2153 QLine QVariant::toLine() const
2155 return qVariantToHelper<QLine>(d, handlerManager);
2159 \fn QPointF QVariant::toPointF() const
2161 Returns the variant as a QPointF if the variant has type() \l
2162 Point or \l PointF; otherwise returns a null QPointF.
2164 \sa canConvert(), convert()
2166 QPointF QVariant::toPointF() const
2168 return qVariantToHelper<QPointF>(d, handlerManager);
2171 #endif // QT_NO_GEOM_VARIANT
2173 #ifndef QT_BOOTSTRAPPED
2175 \fn QUrl QVariant::toUrl() const
2177 Returns the variant as a QUrl if the variant has type()
2178 \l Url; otherwise returns an invalid QUrl.
2180 \sa canConvert(), convert()
2182 QUrl QVariant::toUrl() const
2184 return qVariantToHelper<QUrl>(d, handlerManager);
2189 \fn QLocale QVariant::toLocale() const
2191 Returns the variant as a QLocale if the variant has type()
2192 \l Locale; otherwise returns an invalid QLocale.
2194 \sa canConvert(), convert()
2196 QLocale QVariant::toLocale() const
2198 return qVariantToHelper<QLocale>(d, handlerManager);
2202 \fn QRegExp QVariant::toRegExp() const
2205 Returns the variant as a QRegExp if the variant has type() \l
2206 RegExp; otherwise returns an empty QRegExp.
2208 \sa canConvert(), convert()
2210 #ifndef QT_NO_REGEXP
2211 QRegExp QVariant::toRegExp() const
2213 return qVariantToHelper<QRegExp>(d, handlerManager);
2218 \fn QRegularExpression QVariant::toRegularExpression() const
2221 Returns the variant as a QRegularExpression if the variant has type() \l
2222 QRegularExpression; otherwise returns an empty QRegularExpression.
2224 \sa canConvert(), convert()
2226 #ifndef QT_BOOTSTRAPPED
2227 #ifndef QT_NO_REGEXP
2228 QRegularExpression QVariant::toRegularExpression() const
2230 return qVariantToHelper<QRegularExpression>(d, handlerManager);
2237 Returns the variant as a QUuid if the variant has type() \l
2238 QUuid; otherwise returns a default constructed QUuid.
2240 \sa canConvert(), convert()
2242 QUuid QVariant::toUuid() const
2244 return qVariantToHelper<QUuid>(d, handlerManager);
2250 Returns the variant as a QModelIndex if the variant has type() \l
2251 QModelIndex; otherwise returns a default constructed QModelIndex.
2253 \sa canConvert(), convert()
2255 QModelIndex QVariant::toModelIndex() const
2257 return qVariantToHelper<QModelIndex>(d, handlerManager);
2263 Returns the variant as a QJsonValue if the variant has type() \l
2264 QJsonValue; otherwise returns a default constructed QJsonValue.
2266 \sa canConvert(), convert()
2268 QJsonValue QVariant::toJsonValue() const
2270 return qVariantToHelper<QJsonValue>(d, handlerManager);
2276 Returns the variant as a QJsonObject if the variant has type() \l
2277 QJsonObject; otherwise returns a default constructed QJsonObject.
2279 \sa canConvert(), convert()
2281 QJsonObject QVariant::toJsonObject() const
2283 return qVariantToHelper<QJsonObject>(d, handlerManager);
2289 Returns the variant as a QJsonArray if the variant has type() \l
2290 QJsonArray; otherwise returns a default constructed QJsonArray.
2292 \sa canConvert(), convert()
2294 QJsonArray QVariant::toJsonArray() const
2296 return qVariantToHelper<QJsonArray>(d, handlerManager);
2302 Returns the variant as a QJsonDocument if the variant has type() \l
2303 QJsonDocument; otherwise returns a default constructed QJsonDocument.
2305 \sa canConvert(), convert()
2307 QJsonDocument QVariant::toJsonDocument() const
2309 return qVariantToHelper<QJsonDocument>(d, handlerManager);
2314 \fn QChar QVariant::toChar() const
2316 Returns the variant as a QChar if the variant has type() \l Char,
2317 \l Int, or \l UInt; otherwise returns an invalid QChar.
2319 \sa canConvert(), convert()
2321 QChar QVariant::toChar() const
2323 return qVariantToHelper<QChar>(d, handlerManager);
2327 Returns the variant as a QBitArray if the variant has type()
2328 \l BitArray; otherwise returns an empty bit array.
2330 \sa canConvert(), convert()
2332 QBitArray QVariant::toBitArray() const
2334 return qVariantToHelper<QBitArray>(d, handlerManager);
2337 template <typename T>
2338 inline T qNumVariantToHelper(const QVariant::Private &d,
2339 const HandlersManager &handlerManager, bool *ok, const T& val)
2341 uint t = qMetaTypeId<T>();
2348 if (!handlerManager[d.type]->convert(&d, t, &ret, ok) && ok)
2354 Returns the variant as an int if the variant has type() \l Int,
2355 \l Bool, \l ByteArray, \l Char, \l Double, \l LongLong, \l
2356 String, \l UInt, or \l ULongLong; otherwise returns 0.
2358 If \a ok is non-null: \c{*}\a{ok} is set to true if the value could be
2359 converted to an int; otherwise \c{*}\a{ok} is set to false.
2361 \b{Warning:} If the value is convertible to a \l LongLong but is too
2362 large to be represented in an int, the resulting arithmetic overflow will
2363 not be reflected in \a ok. A simple workaround is to use QString::toInt().
2365 \sa canConvert(), convert()
2367 int QVariant::toInt(bool *ok) const
2369 return qNumVariantToHelper<int>(d, handlerManager, ok, d.data.i);
2373 Returns the variant as an unsigned int if the variant has type()
2374 \l UInt, \l Bool, \l ByteArray, \l Char, \l Double, \l Int, \l
2375 LongLong, \l String, or \l ULongLong; otherwise returns 0.
2377 If \a ok is non-null: \c{*}\a{ok} is set to true if the value could be
2378 converted to an unsigned int; otherwise \c{*}\a{ok} is set to false.
2380 \b{Warning:} If the value is convertible to a \l ULongLong but is too
2381 large to be represented in an unsigned int, the resulting arithmetic overflow will
2382 not be reflected in \a ok. A simple workaround is to use QString::toUInt().
2384 \sa canConvert(), convert()
2386 uint QVariant::toUInt(bool *ok) const
2388 return qNumVariantToHelper<uint>(d, handlerManager, ok, d.data.u);
2392 Returns the variant as a long long int if the variant has type()
2393 \l LongLong, \l Bool, \l ByteArray, \l Char, \l Double, \l Int,
2394 \l String, \l UInt, or \l ULongLong; otherwise returns 0.
2396 If \a ok is non-null: \c{*}\c{ok} is set to true if the value could be
2397 converted to an int; otherwise \c{*}\c{ok} is set to false.
2399 \sa canConvert(), convert()
2401 qlonglong QVariant::toLongLong(bool *ok) const
2403 return qNumVariantToHelper<qlonglong>(d, handlerManager, ok, d.data.ll);
2407 Returns the variant as as an unsigned long long int if the
2408 variant has type() \l ULongLong, \l Bool, \l ByteArray, \l Char,
2409 \l Double, \l Int, \l LongLong, \l String, or \l UInt; otherwise
2412 If \a ok is non-null: \c{*}\a{ok} is set to true if the value could be
2413 converted to an int; otherwise \c{*}\a{ok} is set to false.
2415 \sa canConvert(), convert()
2417 qulonglong QVariant::toULongLong(bool *ok) const
2419 return qNumVariantToHelper<qulonglong>(d, handlerManager, ok, d.data.ull);
2423 Returns the variant as a bool if the variant has type() Bool.
2425 Returns true if the variant has type() \l Bool, \l Char, \l Double,
2426 \l Int, \l LongLong, \l UInt, or \l ULongLong and the value is
2427 non-zero, or if the variant has type \l String or \l ByteArray and
2428 its lower-case content is not one of the following: empty, "0"
2429 or "false"; otherwise returns false.
2431 \sa canConvert(), convert()
2433 bool QVariant::toBool() const
2439 handlerManager[d.type]->convert(&d, Bool, &res, 0);
2445 Returns the variant as a double if the variant has type() \l
2446 Double, \l QMetaType::Float, \l Bool, \l ByteArray, \l Int, \l LongLong, \l String, \l
2447 UInt, or \l ULongLong; otherwise returns 0.0.
2449 If \a ok is non-null: \c{*}\a{ok} is set to true if the value could be
2450 converted to a double; otherwise \c{*}\a{ok} is set to false.
2452 \sa canConvert(), convert()
2454 double QVariant::toDouble(bool *ok) const
2456 return qNumVariantToHelper<double>(d, handlerManager, ok, d.data.d);
2460 Returns the variant as a float if the variant has type() \l
2461 Double, \l QMetaType::Float, \l Bool, \l ByteArray, \l Int, \l LongLong, \l String, \l
2462 UInt, or \l ULongLong; otherwise returns 0.0.
2466 If \a ok is non-null: \c{*}\a{ok} is set to true if the value could be
2467 converted to a double; otherwise \c{*}\a{ok} is set to false.
2469 \sa canConvert(), convert()
2471 float QVariant::toFloat(bool *ok) const
2473 return qNumVariantToHelper<float>(d, handlerManager, ok, d.data.f);
2477 Returns the variant as a qreal if the variant has type() \l
2478 Double, \l QMetaType::Float, \l Bool, \l ByteArray, \l Int, \l LongLong, \l String, \l
2479 UInt, or \l ULongLong; otherwise returns 0.0.
2483 If \a ok is non-null: \c{*}\a{ok} is set to true if the value could be
2484 converted to a double; otherwise \c{*}\a{ok} is set to false.
2486 \sa canConvert(), convert()
2488 qreal QVariant::toReal(bool *ok) const
2490 return qNumVariantToHelper<qreal>(d, handlerManager, ok, d.data.real);
2494 Returns the variant as a QVariantList if the variant has type()
2495 \l List or \l StringList; otherwise returns an empty list.
2497 \sa canConvert(), convert()
2499 QVariantList QVariant::toList() const
2501 return qVariantToHelper<QVariantList>(d, handlerManager);
2505 static const quint32 qCanConvertMatrix[QVariant::LastCoreType + 1] =
2509 /*Bool*/ 1 << QVariant::Double | 1 << QVariant::Int | 1 << QVariant::UInt
2510 | 1 << QVariant::LongLong | 1 << QVariant::ULongLong | 1 << QVariant::ByteArray
2511 | 1 << QVariant::String | 1 << QVariant::Char,
2513 /*Int*/ 1 << QVariant::UInt | 1 << QVariant::String | 1 << QVariant::Double
2514 | 1 << QVariant::Bool | 1 << QVariant::LongLong | 1 << QVariant::ULongLong
2515 | 1 << QVariant::Char | 1 << QVariant::ByteArray,
2517 /*UInt*/ 1 << QVariant::Int | 1 << QVariant::String | 1 << QVariant::Double
2518 | 1 << QVariant::Bool | 1 << QVariant::LongLong | 1 << QVariant::ULongLong
2519 | 1 << QVariant::Char | 1 << QVariant::ByteArray,
2521 /*LLong*/ 1 << QVariant::Int | 1 << QVariant::String | 1 << QVariant::Double
2522 | 1 << QVariant::Bool | 1 << QVariant::UInt | 1 << QVariant::ULongLong
2523 | 1 << QVariant::Char | 1 << QVariant::ByteArray,
2525 /*ULlong*/ 1 << QVariant::Int | 1 << QVariant::String | 1 << QVariant::Double
2526 | 1 << QVariant::Bool | 1 << QVariant::UInt | 1 << QVariant::LongLong
2527 | 1 << QVariant::Char | 1 << QVariant::ByteArray,
2529 /*double*/ 1 << QVariant::Int | 1 << QVariant::String | 1 << QVariant::ULongLong
2530 | 1 << QVariant::Bool | 1 << QVariant::UInt | 1 << QVariant::LongLong
2531 | 1 << QVariant::ByteArray,
2533 /*QChar*/ 1 << QVariant::Int | 1 << QVariant::UInt | 1 << QVariant::LongLong
2534 | 1 << QVariant::ULongLong,
2538 /*QList*/ 1 << QVariant::StringList,
2540 /*QString*/ 1 << QVariant::StringList | 1 << QVariant::ByteArray | 1 << QVariant::Int
2541 | 1 << QVariant::UInt | 1 << QVariant::Bool | 1 << QVariant::Double
2542 | 1 << QVariant::Date | 1 << QVariant::Time | 1 << QVariant::DateTime
2543 | 1 << QVariant::LongLong | 1 << QVariant::ULongLong | 1 << QVariant::Char
2544 | 1 << QVariant::Url | 1 << QVariant::Uuid,
2546 /*QStringList*/ 1 << QVariant::List | 1 << QVariant::String,
2548 /*QByteArray*/ 1 << QVariant::String | 1 << QVariant::Int | 1 << QVariant::UInt | 1 << QVariant::Bool
2549 | 1 << QVariant::Double | 1 << QVariant::LongLong | 1 << QVariant::ULongLong,
2553 /*QDate*/ 1 << QVariant::String | 1 << QVariant::DateTime,
2555 /*QTime*/ 1 << QVariant::String | 1 << QVariant::DateTime,
2557 /*QDateTime*/ 1 << QVariant::String | 1 << QVariant::Date,
2559 /*QUrl*/ 1 << QVariant::String,
2563 /*QRect*/ 1 << QVariant::RectF,
2565 /*QRectF*/ 1 << QVariant::Rect,
2567 /*QSize*/ 1 << QVariant::SizeF,
2569 /*QSizeF*/ 1 << QVariant::Size,
2571 /*QLine*/ 1 << QVariant::LineF,
2573 /*QLineF*/ 1 << QVariant::Line,
2575 /*QPoint*/ 1 << QVariant::PointF,
2577 /*QPointF*/ 1 << QVariant::Point,
2585 /*QUuid*/ 1 << QVariant::String
2588 #ifndef QT_BOOTSTRAPPED
2590 Returns true if from inherits to.
2592 static bool canConvertMetaObject(const QMetaObject *from, const QMetaObject *to)
2594 if (from && to == &QObject::staticMetaObject)
2600 from = from->superClass();
2607 static bool canConvertMetaObject(int fromId, int toId, QObject *fromObject)
2609 #ifndef QT_BOOTSTRAPPED
2610 QMetaType toType(toId);
2611 if ((QMetaType::typeFlags(fromId) & QMetaType::PointerToQObject) && (toType.flags() & QMetaType::PointerToQObject)) {
2614 return canConvertMetaObject(fromObject->metaObject(), toType.metaObject());
2619 Q_UNUSED(fromObject);
2626 Returns true if the variant's type can be cast to the requested
2627 type, \a targetTypeId. Such casting is done automatically when calling the
2628 toInt(), toBool(), ... methods.
2630 The following casts are done automatically:
2633 \header \li Type \li Automatically Cast To
2634 \row \li \l Bool \li \l Char, \l Double, \l Int, \l LongLong, \l String, \l UInt, \l ULongLong
2635 \row \li \l ByteArray \li \l Double, \l Int, \l LongLong, \l String, \l UInt, \l ULongLong
2636 \row \li \l Char \li \l Bool, \l Int, \l UInt, \l LongLong, \l ULongLong
2637 \row \li \l Color \li \l String
2638 \row \li \l Date \li \l DateTime, \l String
2639 \row \li \l DateTime \li \l Date, \l String, \l Time
2640 \row \li \l Double \li \l Bool, \l Int, \l LongLong, \l String, \l UInt, \l ULongLong
2641 \row \li \l Font \li \l String
2642 \row \li \l Int \li \l Bool, \l Char, \l Double, \l LongLong, \l String, \l UInt, \l ULongLong
2643 \row \li \l KeySequence \li \l Int, \l String
2644 \row \li \l List \li \l StringList (if the list's items can be converted to strings)
2645 \row \li \l LongLong \li \l Bool, \l ByteArray, \l Char, \l Double, \l Int, \l String, \l UInt, \l ULongLong
2646 \row \li \l Point \li PointF
2647 \row \li \l Rect \li RectF
2648 \row \li \l String \li \l Bool, \l ByteArray, \l Char, \l Color, \l Date, \l DateTime, \l Double,
2649 \l Font, \l Int, \l KeySequence, \l LongLong, \l StringList, \l Time, \l UInt,
2651 \row \li \l StringList \li \l List, \l String (if the list contains exactly one item)
2652 \row \li \l Time \li \l String
2653 \row \li \l UInt \li \l Bool, \l Char, \l Double, \l Int, \l LongLong, \l String, \l ULongLong
2654 \row \li \l ULongLong \li \l Bool, \l Char, \l Double, \l Int, \l LongLong, \l String, \l UInt
2657 A QVariant containing a pointer to a type derived from QObject will also return true for this
2658 function if a qobject_cast to the type described by \a targetTypeId would succeed. Note that
2659 this only works for QObject subclasses which use the Q_OBJECT macro.
2663 bool QVariant::canConvert(int targetTypeId) const
2665 // TODO Reimplement this function, currently it works but it is a historical mess.
2666 uint currentType = ((d.type == QMetaType::Float) ? QVariant::Double : d.type);
2667 if (currentType == QMetaType::SChar || currentType == QMetaType::Char)
2668 currentType = QMetaType::UInt;
2669 if (targetTypeId == QMetaType::SChar || currentType == QMetaType::Char)
2670 targetTypeId = QMetaType::UInt;
2671 if (uint(targetTypeId) == uint(QMetaType::Float)) targetTypeId = QVariant::Double;
2674 if (currentType == uint(targetTypeId))
2677 if (targetTypeId < 0)
2679 if (targetTypeId >= QMetaType::User)
2680 return canConvertMetaObject(currentType, targetTypeId, d.data.o);
2682 // FIXME It should be LastCoreType intead of Uuid
2683 if (currentType > int(QMetaType::QUuid) || targetTypeId > int(QMetaType::QUuid)) {
2684 switch (uint(targetTypeId)) {
2686 if (currentType == QVariant::KeySequence)
2689 case QVariant::UInt:
2690 return currentType == QMetaType::ULong
2691 || currentType == QMetaType::Long
2692 || currentType == QMetaType::UShort
2693 || currentType == QMetaType::UChar
2694 || currentType == QMetaType::Char
2695 || currentType == QMetaType::SChar
2696 || currentType == QMetaType::Short;
2697 case QVariant::Image:
2698 return currentType == QVariant::Pixmap || currentType == QVariant::Bitmap;
2699 case QVariant::Pixmap:
2700 return currentType == QVariant::Image || currentType == QVariant::Bitmap
2701 || currentType == QVariant::Brush;
2702 case QVariant::Bitmap:
2703 return currentType == QVariant::Pixmap || currentType == QVariant::Image;
2704 case QVariant::ByteArray:
2705 return currentType == QVariant::Color;
2706 case QVariant::String:
2707 return currentType == QVariant::KeySequence || currentType == QVariant::Font
2708 || currentType == QVariant::Color;
2709 case QVariant::KeySequence:
2710 return currentType == QVariant::String || currentType == QVariant::Int;
2711 case QVariant::Font:
2712 return currentType == QVariant::String;
2713 case QVariant::Color:
2714 return currentType == QVariant::String || currentType == QVariant::ByteArray
2715 || currentType == QVariant::Brush;
2716 case QVariant::Brush:
2717 return currentType == QVariant::Color || currentType == QVariant::Pixmap;
2718 case QMetaType::Long:
2719 case QMetaType::Char:
2720 case QMetaType::SChar:
2721 case QMetaType::UChar:
2722 case QMetaType::ULong:
2723 case QMetaType::Short:
2724 case QMetaType::UShort:
2725 return qCanConvertMatrix[QVariant::Int] & (1 << currentType) || currentType == QVariant::Int;
2726 case QMetaType::QObjectStar:
2727 return canConvertMetaObject(currentType, targetTypeId, d.data.o);
2733 if (targetTypeId == String && currentType == StringList)
2734 return v_cast<QStringList>(&d)->count() == 1;
2735 return qCanConvertMatrix[targetTypeId] & (1 << currentType);
2739 Casts the variant to the requested type, \a targetTypeId. If the cast cannot be
2740 done, the variant is cleared. Returns true if the current type of
2741 the variant was successfully cast; otherwise returns false.
2743 A QVariant containing a pointer to a type derived from QObject will also convert
2744 and return true for this function if a qobject_cast to the type described
2745 by \a targetTypeId would succeed. Note that this only works for QObject subclasses
2746 which use the Q_OBJECT macro.
2748 \warning For historical reasons, converting a null QVariant results
2749 in a null value of the desired type (e.g., an empty string for
2750 QString) and a result of false.
2752 \sa canConvert(), clear()
2755 bool QVariant::convert(int targetTypeId)
2757 if (d.type == uint(targetTypeId))
2760 QVariant oldValue = *this;
2763 if (!oldValue.canConvert(targetTypeId))
2766 create(targetTypeId, 0);
2767 if (oldValue.isNull())
2770 if ((QMetaType::typeFlags(d.type) & QMetaType::PointerToQObject) && (QMetaType::typeFlags(targetTypeId) & QMetaType::PointerToQObject)) {
2771 create(targetTypeId, &oldValue.d.data.o);
2776 if (!handlerManager[d.type]->convert(&oldValue.d, targetTypeId, data(), &isOk))
2783 \fn bool QVariant::convert(const int type, void *ptr) const
2785 Created for qvariant_cast() usage
2787 bool QVariant::convert(const int type, void *ptr) const
2789 Q_ASSERT(type < int(QMetaType::User));
2790 return handlerManager[type]->convert(&d, type, ptr, 0);
2795 \fn bool operator==(const QVariant &v1, const QVariant &v2)
2799 Returns true if \a v1 and \a v2 are equal; otherwise returns false.
2801 If \a v1 and \a v2 have the same \l{QVariant::}{type()}, the
2802 type's equality operator is used for comparison. If not, it is
2803 attempted to \l{QVariant::}{convert()} \a v2 to the same type as
2804 \a v1. See \l{QVariant::}{canConvert()} for a list of possible
2807 The result of the function is not affected by the result of QVariant::isNull,
2808 which means that two values can be equal even if one of them is null and
2811 \warning This function doesn't support custom types registered
2812 with qRegisterMetaType().
2815 \fn bool operator!=(const QVariant &v1, const QVariant &v2)
2819 Returns false if \a v1 and \a v2 are equal; otherwise returns true.
2821 \warning This function doesn't support custom types registered
2822 with qRegisterMetaType().
2825 /*! \fn bool QVariant::operator==(const QVariant &v) const
2827 Compares this QVariant with \a v and returns true if they are
2828 equal; otherwise returns false.
2830 QVariant uses the equality operator of the type() it contains to
2831 check for equality. QVariant will try to convert() \a v if its
2832 type is not the same as this variant's type. See canConvert() for
2833 a list of possible conversions.
2835 \warning This function doesn't support custom types registered
2836 with qRegisterMetaType().
2840 \fn bool QVariant::operator!=(const QVariant &v) const
2842 Compares this QVariant with \a v and returns true if they are not
2843 equal; otherwise returns false.
2845 \warning This function doesn't support custom types registered
2846 with qRegisterMetaType().
2849 static bool qIsNumericType(uint tp)
2851 return (tp >= QVariant::Bool && tp <= QVariant::Double)
2852 || (tp >= QMetaType::Long && tp <= QMetaType::Float);
2855 static bool qIsFloatingPoint(uint tp)
2857 return tp == QVariant::Double || tp == QMetaType::Float;
2863 bool QVariant::cmp(const QVariant &v) const
2866 if (d.type != v2.d.type) {
2867 if (qIsNumericType(d.type) && qIsNumericType(v.d.type)) {
2868 if (qIsFloatingPoint(d.type) || qIsFloatingPoint(v.d.type))
2869 return qFuzzyCompare(toReal(), v.toReal());
2871 return toLongLong() == v.toLongLong();
2873 if (!v2.canConvert(d.type) || !v2.convert(d.type))
2876 return handlerManager[d.type]->compare(&d, &v2.d);
2883 const void *QVariant::constData() const
2885 return d.is_shared ? d.data.shared->ptr : reinterpret_cast<const void *>(&d.data.ptr);
2889 \fn const void* QVariant::data() const
2897 void* QVariant::data()
2900 return const_cast<void *>(constData());
2905 Returns true if this is a null variant, false otherwise. A variant is
2906 considered null if it contains a default constructed value or a built-in
2907 type instance that has an isNull method, in which case the result
2908 would be the same as calling isNull on the wrapped object.
2910 \warning The result of the function doesn't affect == operator, which means
2911 that two values can be equal even if one of them is null and another is not.
2913 bool QVariant::isNull() const
2915 return handlerManager[d.type]->isNull(&d);
2918 #ifndef QT_NO_DEBUG_STREAM
2919 QDebug operator<<(QDebug dbg, const QVariant &v)
2921 const uint typeId = v.d.type;
2922 dbg.nospace() << "QVariant(";
2923 if (typeId != QMetaType::UnknownType) {
2924 dbg.nospace() << QMetaType::typeName(typeId) << ", ";
2925 handlerManager[typeId]->debugStream(dbg, v);
2927 dbg.nospace() << "Invalid";
2929 dbg.nospace() << ')';
2933 QDebug operator<<(QDebug dbg, const QVariant::Type p)
2935 dbg.nospace() << "QVariant::"
2936 << (int(p) != int(QMetaType::UnknownType)
2937 ? QMetaType::typeName(p)
2944 /*! \fn void QVariant::setValue(const T &value)
2946 Stores a copy of \a value. If \c{T} is a type that QVariant
2947 doesn't support, QMetaType is used to store the value. A compile
2948 error will occur if QMetaType doesn't handle the type.
2952 \snippet code/src_corelib_kernel_qvariant.cpp 4
2954 \sa value(), fromValue(), canConvert()
2957 /*! \fn T QVariant::value() const
2959 Returns the stored value converted to the template type \c{T}.
2960 Call canConvert() to find out whether a type can be converted.
2961 If the value cannot be converted, \l{default-constructed value}
2964 If the type \c{T} is supported by QVariant, this function behaves
2965 exactly as toString(), toInt() etc.
2969 \snippet code/src_corelib_kernel_qvariant.cpp 5
2971 If the QVariant contains a pointer to a type derived from QObject then
2972 \c{T} may be any QObject type. If the pointer stored in the QVariant can be
2973 qobject_cast to T, then that result is returned. Otherwise a null pointer is
2974 returned. Note that this only works for QObject subclasses which use the
2977 \sa setValue(), fromValue(), canConvert()
2980 /*! \fn bool QVariant::canConvert() const
2982 Returns true if the variant can be converted to the template type \c{T},
2987 \snippet code/src_corelib_kernel_qvariant.cpp 6
2989 A QVariant containing a pointer to a type derived from QObject will also return true for this
2990 function if a qobject_cast to the template type \c{T} would succeed. Note that this only works
2991 for QObject subclasses which use the Q_OBJECT macro.
2996 /*! \fn static QVariant QVariant::fromValue(const T &value)
2998 Returns a QVariant containing a copy of \a value. Behaves
2999 exactly like setValue() otherwise.
3003 \snippet code/src_corelib_kernel_qvariant.cpp 7
3005 \note If you are working with custom types, you should use
3006 the Q_DECLARE_METATYPE() macro to register your custom type.
3008 \sa setValue(), value()
3012 \fn QVariant qVariantFromValue(const T &value)
3016 Returns a variant containing a copy of the given \a value
3017 with template type \c{T}.
3019 This function is equivalent to QVariant::fromValue(\a value).
3021 \note This function was provided as a workaround for MSVC 6
3022 which did not support member template functions. It is advised
3023 to use the other form in new code.
3025 For example, a QObject pointer can be stored in a variant with the
3028 \snippet code/src_corelib_kernel_qvariant.cpp 8
3030 \sa QVariant::fromValue()
3033 /*! \fn void qVariantSetValue(QVariant &variant, const T &value)
3037 Sets the contents of the given \a variant to a copy of the
3038 \a value with the specified template type \c{T}.
3040 This function is equivalent to QVariant::setValue(\a value).
3042 \note This function was provided as a workaround for MSVC 6
3043 which did not support member template functions. It is advised
3044 to use the other form in new code.
3046 \sa QVariant::setValue()
3050 \fn T qvariant_cast(const QVariant &value)
3053 Returns the given \a value converted to the template type \c{T}.
3055 This function is equivalent to QVariant::value().
3057 \sa QVariant::value()
3060 /*! \fn T qVariantValue(const QVariant &value)
3064 Returns the given \a value converted to the template type \c{T}.
3066 This function is equivalent to
3067 \l{QVariant::value()}{QVariant::value}<T>(\a value).
3069 \note This function was provided as a workaround for MSVC 6
3070 which did not support member template functions. It is advised
3071 to use the other form in new code.
3073 \sa QVariant::value(), qvariant_cast()
3076 /*! \fn bool qVariantCanConvert(const QVariant &value)
3080 Returns true if the given \a value can be converted to the
3081 template type specified; otherwise returns false.
3083 This function is equivalent to QVariant::canConvert(\a value).
3085 \note This function was provided as a workaround for MSVC 6
3086 which did not support member template functions. It is advised
3087 to use the other form in new code.
3089 \sa QVariant::canConvert()
3093 \typedef QVariantList
3096 Synonym for QList<QVariant>.
3100 \typedef QVariantMap
3103 Synonym for QMap<QString, QVariant>.
3107 \typedef QVariantHash
3111 Synonym for QHash<QString, QVariant>.
3115 \typedef QVariant::DataPtr
3120 \fn DataPtr &QVariant::data_ptr()
3125 \fn const DataPtr &QVariant::data_ptr() const