Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    Solved QVariant wrong cast

    General and Desktop
    qvariant custom type
    2
    4
    1217
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • J
      jj382 last edited by

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

       #include <QApplication>
       #include <QVariant>
       
       class CustomClass1
       {
       public: 
         CustomClass1() = default;
         int a = 0;
       };
       
       Q_DECLARE_METATYPE(CustomClass1)
       
       template <typename T>
       QVariant variantify(T &&x)
       {
         QVariant variant;
         variant.setValue(std::forward<T>(x));
         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
           }
         else
           {
             qDebug() << "conversion failed";
           }
       
         return app.exec();
       }
      

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

      1 Reply Last reply Reply Quote 0
      • Chris Kawa
        Chris Kawa Moderators last edited by

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

        J 2 Replies Last reply Reply Quote 0
        • J
          jj382 @Chris Kawa last edited by

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

          1 Reply Last reply Reply Quote 0
          • J
            jj382 @Chris Kawa last edited by

            @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.

            1 Reply Last reply Reply Quote 0
            • First post
              Last post