QVariant.canConvert inconsistencies



  • Hi there,

    following minimized problem:

    @
    #include <QtCore/QCoreApplication>
    #include <QVariant>
    #include <QDebug>
    #include <stdexcept>

    template <typename Type>
    Type get(QVariant& source)
    {
    if(source.canConvert<Type>())
    return source.value<Type>();
    else
    throw std::runtime_error("Invalid type");
    }

    int main(int argc, char *argv[])
    {
    QVariant variant;
    variant.setValue(QString("blabla"));

    qDebug() << get<double>(variant); // "0"

    }
    @

    Obviously, QVariant.canConvert returns true and the string "blabla" gets converted into a double with the value 0 (zero) as the application does not throw an exception. Storing and/or querying other types result in the same value, better say the same "problem" because it seems that nearly any type can be converted into any other type but the return value my be zero (I write nearly because we haven't checked all types)

    Why?
    And is there a workaround which gives us a template based posibility to check the stored type.
    We used boost::lexical_cast before switching to QVariant as we through that QVariant would be the easier solution.

    greets.
    an ky



  • canConvert makes a static check, whether the type can be converted, not if the conversion can really be done. nearly everything can be converted to/from a string.



  • Hi Gerolf,

    is there a way to do dynamic checks?


  • Moderators

    There is also "type":http://doc.qt.nokia.com/4.7/qvariant.html#type for checks available.



  • AFAIK, QVariant does not offer them.
    You have to do them on your own.

    But it will be tricky, becaus:

    Is a date convertable to a long? yes --> seconds since..., or no ?

    is a double convertable to an int, if it contains no int values, like 2.567 ?


Log in to reply
 

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