Cannot connect signal from base class

前端 未结 2 1454
傲寒
傲寒 2021-01-20 21:58

When I try to connect a BASE class signal, Qt tells me the signal does not exists on the DERIVED class.

Why is that? How can I tell connect to use the BASE class?

相关标签:
2条回答
  • 2021-01-20 22:39

    Your problem is that you're multiply deriving Derived from QObject: you derive from it directly and through the Base class. Don't do that, since Qt doesn't support multiple derivation from QObject, not even virtual derivation.

    The second and subsequent QObject bases are ignored by the QObject system. Thus, to the QObject machinery, the Derived class only derives from QObject, and not from Base - thus it doesn't know about baseSignal. As they well should be, since the support of multiple QObject derivation would incur runtime overheads - and in any case, you'd need to virtually inherit QObject, and you didn't even do that!

    At the very minimum, if you expected such to work, your code would need to look as follows:

    class Base : public virtual QObject { ... };
    class Derived : public Base, public QObject { ... };
    

    ... but Qt doesn't support that.

    You'd have been luckier if you wrote the Derived class to inherit the base class first:

    class Base : public QObject { ... };
    class Derived : public Base, public QObject { ... };
    

    This would have worked, although the second QObject base would be pointless and ignored by the QObject machinery.

    0 讨论(0)
  • 2021-01-20 22:45

    It would be much better in this form:

    namespace MyNamespace 
    {
    
    class Base : public QObject
    {
        Q_OBJECT
    
    signals:
        void baseSignal();
    };
    
    class Derived : public Base
    {
        Q_OBJECT
    
    signals:
        void derivedSignal();
    };
    
    void registerX( Derived* derived )
    {
        QObject::connect( derived, SIGNAL(baseSignal()), foo, SLOT(fooSlot()));
    }
    
    } // namespace MyNamespace
    

    As this post says you shall not inherit QObject multiple times.

    0 讨论(0)
提交回复
热议问题