Fix QVariant(QString) <-> enum conversion

A QVariant(QString) was not convertible to an enum not registered with
Q_ENUM() which worked fine in Qt5.
The same problem exists for QVariant(enum) to QString.
Fix it by not bailing out when no metatype for the enum was found and
try to convert it to a qlonglong instead (which is then correctly
converted to the enum type).

Fixes: QTBUG-109744
Pick-to: 6.5 6.4
Change-Id: Ie7bb016a860455b69508f0f46b36474c9c294f3a
Reviewed-by: Thiago Macieira <thiago.macieira@intel.com>
bb10
Christian Ehrlicher 2023-02-03 17:31:11 +01:00
parent e30ed4d431
commit 66a1a71f1f
2 changed files with 15 additions and 7 deletions

View File

@ -1947,7 +1947,6 @@ static bool convertFromEnum(QMetaType fromType, const void *from, QMetaType toTy
if (toType.id() != QMetaType::QString && toType.id() != QMetaType::QByteArray)
return QMetaType::convert(QMetaType::fromType<qlonglong>(), &ll, toType, to);
}
Q_ASSERT(toType.id() == QMetaType::QString || toType.id() == QMetaType::QByteArray);
#ifndef QT_NO_QOBJECT
QMetaEnum en = metaEnumFromType(fromType);
if (en.isValid()) {
@ -1967,6 +1966,8 @@ static bool convertFromEnum(QMetaType fromType, const void *from, QMetaType toTy
return true;
}
#endif
if (toType.id() == QMetaType::QString || toType.id() == QMetaType::QByteArray)
return QMetaType::convert(QMetaType::fromType<qlonglong>(), &ll, toType, to);
return false;
}
@ -1978,12 +1979,12 @@ static bool convertToEnum(QMetaType fromType, const void *from, QMetaType toType
#ifndef QT_NO_QOBJECT
if (fromTypeId == QMetaType::QString || fromTypeId == QMetaType::QByteArray) {
QMetaEnum en = metaEnumFromType(toType);
if (!en.isValid())
return false;
QByteArray keys = (fromTypeId == QMetaType::QString)
? static_cast<const QString *>(from)->toUtf8()
: *static_cast<const QByteArray *>(from);
value = en.keysToValue(keys.constData(), &ok);
if (en.isValid()) {
QByteArray keys = (fromTypeId == QMetaType::QString)
? static_cast<const QString *>(from)->toUtf8()
: *static_cast<const QByteArray *>(from);
value = en.keysToValue(keys.constData(), &ok);
}
}
#endif
if (!ok) {

View File

@ -4982,6 +4982,13 @@ template <auto value> static void testVariantEnum()
QVERIFY(var2.convert(QMetaType::fromType<int>()));
QCOMPARE(var2.value<int>(), static_cast<int>(value));
QVariant strVar = QString::number(qToUnderlying(value));
QVariant baVar = QByteArray::number(qToUnderlying(value));
QCOMPARE(strVar.value<Enum>(), value);
QCOMPARE(baVar.value<Enum>(), value);
QCOMPARE(var.value<QString>(), strVar);
QCOMPARE(var.value<QByteArray>(), baVar);
// unary + to silence gcc warning
if (losslessConvertToInt) {
int intValue = static_cast<int>(value);