Important: Please read the Qt Code of Conduct -

QVariant to/from QFlag

  • I'm unit testing a function for a table model, where it emits 'headerDataChanged'. One of the fields in this signal is a 'Qt::Orientation' flag. When a QSignalSpy picks it up, the QVariant for the orientation field is an invalid one. I can't cast back to Qt::Orientation. Do I have to locally declare orientation as a metatype? It seems odd it wouldn't just treat it as an int or something.

  • Lifetime Qt Champion


    Can you show the code from that part ?

  • Lifetime Qt Champion

    In Qt 5.7 it seems happy about it
    alt text

      QVariant test;
      Qt::Orientation back = test.value<Qt::Orientation >();
      qDebug() << "i see " << back;

  • This post is deleted!

  • @mrjj It may be that 5.7 has the appropriate behaviour, but 5.5 doesn't seem to. For now, my project seems to be settled on 5.5, so maybe this is just a limitation I have to deal with, but is already fixed in newer Qt versions.

    For a little tester I made a class:

    class Dummy : public QObject
        enum DummyOpt{
            Alpha = 0b01,
            Beta = 0b10
        Q_DECLARE_FLAGS(DummyOpts, DummyOpt)
        explicit Dummy(QObject *parent = nullptr);
        void optionsChanged(DummyOpts);
    public slots:
        void setDummyOpts(DummyOpts o);

    setDummyOpts just emits the optionsChanged signal. In main, I hooked up a QSignalSpy like:

        Dummy d;
        QSignalSpy optionsSpy{&d, &Dummy::optionsChanged};
        QVariant variant =;
        qDebug() << variant.value<Dummy::DummyOpts>();

    And when I compile, I get:

    error: static assertion failed: Type is not registered, please use the Q_DECLARE_METATYPE macro to make it known to Qt's meta-object system
    Q_STATIC_ASSERT_X(QMetaTypeId2<T>::Defined, "Type is not registered, please use the Q_DECLARE_METATYPE macro to make it known to Qt's meta-object system");

  • Lifetime Qt Champion

    @shavera said in QVariant to/from QFlag:


    I dont see you register your own enum anywhere?
    Q_DECLARE_METATYPE (Dummy::DummyOpt);

Log in to reply