QVariant and Enums: different behavior in Qt 5.7 and Qt 5.6.1



  • Hi all,

    I am trying to use QVariant with enum types. My issue is that I have different behaviors when building with Qt 5.7 (run on computer) and building with Qt 5.6.1 (run on embedded target).

    Here is an example code :

    #include <QCoreApplication>
    #include <QMetaType>
    #include <QMetaEnum>
    #include <QVariant>
    #include <QDebug>
    
    enum Test
    {
        Test1,
        Test2,
        Test3
    };
    Q_DECLARE_METATYPE(Test)
    
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
    
        Test t = Test2;
        QVariant v(t);
    
        qDebug()<<"Can convert: "+QString("%1").arg(v.canConvert<Test>());
        Test t2 = v.value<Test>();
        qDebug()<<"Value of t2: "+QString("%1").arg(t2);
    
    
        return a.exec();
    }
    

    Built under Qt 5.7 and running on computer it returns

    Can convert: 1
    Value of t2: 1
    

    Built under Qt 5.6.1 and running on my embedded target it returns

    Can convert: 0
    Value of t2: 0
    

    I cannot figure out why QVariant::canConvert always return false with all enums on my target.

    Thank you for your help.



  • can you try using Q_ENUM?

    globalenums.h

    class GlobalEnums{
    Q_GADGET
    Q_DISABLE_COPY(GlobalEnums)
    GlobalEnums() = delete;
    ~GlobalEnums() = delete;
    public:
    enum Test
    {
        Test1,
        Test2,
        Test3
    };
    Q_ENUM(Test)
    };
    

    main.cpp

    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
    
        GlobalEnums::Test t = GlobalEnums::Test2;
        QVariant v(t);
    
        qDebug()<<"Can convert: " << v.canConvert<GlobalEnums::Test>();
        GlobalEnums::Test t2 = v.value<GlobalEnums::Test>();
        qDebug()<<"Value of t2: "<< t2;
    
    
        return a.exec();
    }
    


  • Thank you VRonin for your help.

    I tried your suggestion but it didn't change the results on my target. Conversion from QVariant to Test enum is still refused.


  • Moderators

    Could be related: QTBUG-53384.
    Can you check with Qt 5.6.2?


Log in to reply
 

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