[SOLVED] 'enum class' with QVariant (How to register strongly typed enum with Qt Meta System?)



  • Solution: Registration of mata-type was not an issue. QVariant does not have constructor taking a template value. In order to use it with custom types from Qt Meta System QVariant::seValue must be used.

    Hi,

    I have been searching but nothing I found worked for me (using Qt 5.3beta) so I figured to ask a new question.

    How to register strongly typed enum with Qt Meta System?

    I have:

    @
    class MyEnums : public QObject
    {
    //Q_ENUMS(Enum)
    public:
    enum class Enum : int
    {
    A,
    B,
    C
    };
    };

    Q_DECLARE_METATYPE(MyEnums::Enum)
    @

    and then elsewhere

    @
    void Class::foo()
    {
    QVariant var(MyEnums::Enum::A);
    }
    @

    which gives me compile error.

    Using

    @
    qRegisterMetaType("MyEnums::Enum");
    @

    also does not work and it tells me the type is not registered and I should use Q_DECLARE_METATYPE macro which I clearly did though...

    Switching to regular enum (i.e. 'enum' instead of 'enum class') works however.

    Also I will require to register the enum with Q_ENUMS as well (as indicated in the first snippet). I am pointing it out in case it could be the problem too.

    Thanks for help!



  • Hi, it works fine with "enum class" and Q_DECLARE_METATYPE in my app, I have also used Q_ENUMS but I think that is only necessary because I use the enum values in QML.
    Is it working if your remove the int type?
    I mean
    @
    enum class Enum // : int
    @
    I did not change the type, but I thought "int" is the default type anyway so it should be exactly the same code if you write " : int" or omit it?



  • Oh I was so dumb... I did not notice that no constructor of QVariant is taking template type. In order to use it with custom types registered QVariant::setValue has to be used instead.



  • Oh sorry I noticed that befre but thought it would also work, I guess you can't use the QVariant constructor for custom types, so replace
    @
    QVariant var(MyEnums::Enum::A);
    @
    with
    @
    QVariant var = QVariant::fromValue(MyEnums::Enum::A);
    @
    and it should work :)

    Edit: haha you changed your post while I was compiling your project, anyway you can use the static function QVariant::fromValue instead of setValue, so this post is not entirely useless i guess. :D



  • Sorry for changing my post, I figured it was redundant given such a simple mistake.

    And thanks a lot for your help! Incidentally that static function you pointed out is actually more useful to me than setValue. :-)


Log in to reply
 

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