-
Bug
-
Resolution: Done
-
Not Evaluated
-
5.3.1
-
None
-
Ubuntu 12.04, GCC 4.8.2
The problem is in template function qNumVariantToHelper which is used by toInt, toDouble, etc:
template <typename T> inline T qNumVariantToHelper(const QVariant::Private &d, const HandlersManager &handlerManager, bool *ok, const T& val) { const uint t = qMetaTypeId<T>(); if (ok) *ok = true; if (d.type == t) return val; T ret = 0; if ((d.type >= QMetaType::User || t >= QMetaType::User) && QMetaType::convert(&val, d.type, &ret, t)) { return ret; } if (!handlerManager[d.type]->convert(&d, t, &ret, ok) && ok) *ok = false; return ret; }
Parameter val is only valid when QVariant has type T, but is used in call to QMetaType::convert when QVariant has custom type.
Here's a test code (c++11):
#include <QCoreApplication>
#include <QMetaType>
#include <QVariant>
#include <iostream>
struct MyCustomType {
int a;
double b;
};
Q_DECLARE_METATYPE(MyCustomType)
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
QMetaType::registerConverter<MyCustomType, double>([](const MyCustomType &val){return val.b;});
QVariant a = QVariant::fromValue(MyCustomType{1000,3.14});
double d = a.value<double>(); // works fine
std::cout << d << std::endl;
bool ok = true;
double dd = a.toDouble(&ok); // doesn't work
std::cout << "ok is " << (ok ? "true" : "false") << std::endl;
std::cout << dd << std::endl;
return 0;
}