Uploaded image for project: 'Qt'
  1. Qt
  2. QTBUG-42322

QVariant::toDouble and similar methods don't work with custom types

    XMLWordPrintable

Details

    • Bug
    • Resolution: Done
    • Not Evaluated
    • 5.4.0 RC
    • 5.3.1
    • Core: Other
    • None
    • Ubuntu 12.04, GCC 4.8.2

    Description

      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;
      }
      

      Attachments

        No reviews matched the request. Check your Options in the drop-down menu of this sections header.

        Activity

          People

            thiago Thiago Macieira
            avkorzun Alexey Korzun
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved:

              Gerrit Reviews

                There are no open Gerrit changes