QML: Try QMetaType conversion in VariantObject's valueOf()

Since we're explicitly dealing with a QVariant here, the metatype
conversion is adequate. We do the same already for toString().

Change-Id: I38c17b40da73ff0f0274e7d65b462eda1af2235a
Reviewed-by: Semih Yavuz <semih.yavuz@qt.io>
Reviewed-by: Fabian Kosmale <fabian.kosmale@qt.io>
This commit is contained in:
Ulf Hermann 2022-11-15 11:53:21 +01:00
parent 0925c51c59
commit 522fc6e6b6
2 changed files with 20 additions and 1 deletions

View File

@ -131,7 +131,17 @@ ReturnedValue VariantPrototype::method_valueOf(const FunctionObject *b, const Va
return Encode(v.toBool());
default:
if (QMetaType(v.metaType()).flags() & QMetaType::IsEnumeration)
RETURN_RESULT(Encode(v.toInt()));
return Encode(v.toInt());
if (v.canConvert<double>())
return Encode(v.toDouble());
if (v.canConvert<int>())
return Encode(v.toInt());
if (v.canConvert<uint>())
return Encode(v.toUInt());
if (v.canConvert<bool>())
return Encode(v.toBool());
if (v.canConvert<QString>())
return Encode(b->engine()->newString(v.toString()));
break;
}
}

View File

@ -5783,6 +5783,14 @@ struct UnknownToJS
void tst_QJSEngine::coerceValue()
{
const UnknownToJS u;
QMetaType::registerConverter<UnknownToJS, int>([](const UnknownToJS &u) {
return u.thing;
});
int v = 0;
QVERIFY(QMetaType::convert(QMetaType::fromType<UnknownToJS>(), &u,
QMetaType::fromType<int>(), &v));
QCOMPARE(v, 13);
QMetaType::registerConverter<UnknownToJS, QTypeRevision>([](const UnknownToJS &u) {
return QTypeRevision::fromMinorVersion(u.thing);
});
@ -5807,6 +5815,7 @@ void tst_QJSEngine::coerceValue()
QCOMPARE((engine.coerceValue<WithToString *, const WithToString *>(&withToString)), &withToString);
QCOMPARE((engine.coerceValue<QString, double>(a)), 5.25);
QCOMPARE((engine.coerceValue<double, QString>(5.25)), a);
QCOMPARE((engine.coerceValue<UnknownToJS, int>(u)), v); // triggers valueOf on a VariantObject
QCOMPARE((engine.coerceValue<UnknownToJS, QTypeRevision>(u)), w);
}