Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. QVariant.canConvert()
Forum Updated to NodeBB v4.3 + New Features

QVariant.canConvert()

Scheduled Pinned Locked Moved Unsolved General and Desktop
3 Posts 2 Posters 609 Views 1 Watching
  • 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.
  • neemeN Offline
    neemeN Offline
    neeme
    wrote on last edited by
    #1
    int a = 100;
    QString str = "very good";
    QVariant v = str;
    if(v.canConvert<int>())
        a = v.value<int>();
    

    why canConvert return true ? "very good" not number!

    1 Reply Last reply
    0
    • neemeN Offline
      neemeN Offline
      neeme
      wrote on last edited by
      #2
      template <typename T>
      void read(QString capstr, QString key, T &val)
      {
          QVariant vt = m_settings->value(capstr + "/" + key, val);
          if(vt.canConvert<T>())
              val = vt.value<T>();
      }
      

      how can i do?

      jsulmJ 1 Reply Last reply
      0
      • neemeN neeme
        template <typename T>
        void read(QString capstr, QString key, T &val)
        {
            QVariant vt = m_settings->value(capstr + "/" + key, val);
            if(vt.canConvert<T>())
                val = vt.value<T>();
        }
        

        how can i do?

        jsulmJ Offline
        jsulmJ Offline
        jsulm
        Lifetime Qt Champion
        wrote on last edited by
        #3

        @neeme See http://doc.qt.io/qt-5/qvariant.html
        "When using canConvert() and convert() consecutively, it is possible for canConvert() to return true, but convert() to return false. This is typically because canConvert() only reports the general ability of QVariant to convert between types given suitable data; it is still possible to supply data which cannot actually be converted."
        Put "123" into your string and you will see that v.value<int>() will return 123 and not 0.
        You should use convert() instead of value(). convert() will return false if the current data in the QVariant cannot be converted to the type you want to convert it to.

        https://forum.qt.io/topic/113070/qt-code-of-conduct

        1 Reply Last reply
        3

        • Login

        • Login or register to search.
        • First post
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • Users
        • Groups
        • Search
        • Get Qt Extensions
        • Unsolved