summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorFabian Kosmale <fabian.kosmale@qt.io>2020-09-29 20:08:00 +0200
committerFabian Kosmale <fabian.kosmale@qt.io>2020-09-30 06:31:36 +0000
commit68923001279fd3da983dc59e57200e2080cadcb6 (patch)
treeb39af86fb12693b620c89235e6657a3098428a62
parent8e2933f140d0969341b2b927f49a4c8606027fcf (diff)
QVariant: Change metatype in convert() even on failure
The documentation of convert promised that “If the cast cannot be done, the variant is still changed to the requested type”. This was not the case so far, because we returned too early if canConvert returned false. This commit changes the behavior of the method to reflect its documentation. The documented behavior seems more useful than the alternative of not changing the metaType, at least for common use cases inside qtdeclarative. Change-Id: I09b5a5efb7344e76e93de278e35c7fb2b2f87dcd Reviewed-by: Thiago Macieira <thiago.macieira@intel.com>
-rw-r--r--src/corelib/kernel/qvariant.cpp2
-rw-r--r--tests/auto/corelib/kernel/qvariant/tst_qvariant.cpp13
2 files changed, 13 insertions, 2 deletions
diff --git a/src/corelib/kernel/qvariant.cpp b/src/corelib/kernel/qvariant.cpp
index f28cd5a7a0f..31c21730725 100644
--- a/src/corelib/kernel/qvariant.cpp
+++ b/src/corelib/kernel/qvariant.cpp
@@ -2032,10 +2032,10 @@ bool QVariant::convert(QMetaType targetType)
QVariant oldValue = *this;
clear();
+ create(targetType.id(), nullptr);
if (!oldValue.canConvert(targetType))
return false;
- create(targetType.id(), nullptr);
// Fail if the value is not initialized or was forced null by a previous failed convert.
if (oldValue.d.is_null && oldValue.d.typeId() != QMetaType::Nullptr)
return false;
diff --git a/tests/auto/corelib/kernel/qvariant/tst_qvariant.cpp b/tests/auto/corelib/kernel/qvariant/tst_qvariant.cpp
index 0eefd95ac7c..ea8f26ae209 100644
--- a/tests/auto/corelib/kernel/qvariant/tst_qvariant.cpp
+++ b/tests/auto/corelib/kernel/qvariant/tst_qvariant.cpp
@@ -99,6 +99,7 @@ private slots:
void canConvert_data();
void canConvert();
+ void convert();
void toSize_data();
void toSize();
@@ -555,6 +556,16 @@ void tst_QVariant::canConvert()
QCOMPARE(val.canConvert(23876), false);
}
+void tst_QVariant::convert()
+{
+ // verify that after convert(), the variant's type has been changed
+ QVariant var = QVariant::fromValue(QString("A string"));
+ var.convert(QMetaType::fromType<int>());
+ QCOMPARE(var.metaType(), QMetaType::fromType<int>());
+ QCOMPARE(var.toInt(), 0);
+}
+
+
void tst_QVariant::toInt_data()
{
QTest::addColumn<QVariant>("value");
@@ -2343,8 +2354,8 @@ void tst_QVariant::qvariant_cast_QObject()
QVERIFY(!data.canConvert(QMetaType::QObjectStar));
QVERIFY(!data.canConvert(::qMetaTypeId<QObject*>()));
QVERIFY(!data.value<QObject*>());
- QVERIFY(!data.convert(QMetaType::QObjectStar));
QVERIFY(data.userType() != QMetaType::QObjectStar);
+ QVERIFY(!data.convert(QMetaType::QObjectStar));
}
}