QVariant wrong cast

  • QVariant casting does not seem to be working right. See testcase below:

     #include <QApplication>
     #include <QVariant>
     class CustomClass1
       CustomClass1() = default;
       int a = 0;
     template <typename T>
     QVariant variantify(T &&x)
       QVariant variant;
       return variant;
     int main(int argc, char *argv[])
       QApplication app(argc, argv);
       CustomClass1 cs;
       cs.a = 1000;
       QVariant const var = variantify(cs);
       if ( var.canConvert<CustomClass1>())
           CustomClass1 const cs_cast = qvariant_cast<CustomClass1>(var);
           qDebug() << "val = " << cs_cast.a; // returns 0
           qDebug() << "conversion failed";
       return app.exec();

    Expecting result: 1000.
    Returned result: 0 (default initialized value)

  • Moderators

    Works for me. Which compiler and what version are you using?

  • @Chris-Kawa Tested with Qt 4.8.6, compiled with msvc2013

  • @Chris-Kawa Please disregard. Sorry. I'm a complete idiot. I had the copy and assignment ctors decorated on my local version of testcase, and it was failing because of that.

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.