Important: Please read the Qt Code of Conduct -

[solved]How to forward declare a Q_Flag for signal/slot connections?

  • // Foo.h
    class Foo : public QObject{
        Q_PROPERTY(fooFlags flags READ flags WRITE setFlags NOTIFY flagsChanged)
        enum Flag{
            fast = 0x01,
            far = 0x02,
            furious = 0x07
        Q_DECLARE_FLAGS(Flags, Flag)
        Foo::Flags flags() const {return m_flags;}
         void flagsChanged(Flags)
    public slots:
        void setFlags(const Flags _flags);
        Flags m_flags;
    // bar.h
    class Foo;
    class Bar : public QObject{
        Bar(Foo* _foo);
    private slots:
        void respondToFooFlagChange(const Foo::Flags& flags);
        Foo* m_foo;
    #include "bar.h"
    #include "foo.h"
    Bar(Foo* _foo)  :  m_foo{ _foo } {
        connect(*_foo, &Foo::flagsChanged,
                this, &Bar::respondToFooFlagChange);
    void Bar::respondToFooFlagChange(const Foo::Flags& flags){
    // Do stuff

    Suppose, for whatever design reasons, I prefer to keep Foo as a forward declared class for Bar. It won't compile because it doesn't know what "Foo::Flags" is. But at the same time, I don't know how forward declare it.

    If enum was a straight c++11 enum class, forward declaration is pretty straightforward.

    I could also hack it by downgrading to int and reconverting from int. But that seems even worse architecturally than just including the Foo header in the Bar header.

    The examples I can see in the Qt Source code seem to include headers rather than using forward declarations, so they're not much help to me.

  • Lifetime Qt Champion


    You can't, the compiler needs to know all the values of the enum in order setup the correct data storage for it.

  • @SGaist thanks, that answers that.

Log in to reply