Multiple Inheritance and Qt Signals

I have a problem with QT regarding multiple inheritance due to QObject. I know that many others have the same problems, but I don’t know how to fix it.

class NavigatableItem : public QObject { Q_OBJECT signals: void deselected(); void selected(); void activated(); }; class Button : public NavigatableItem, public QToolButton { Q_OBJECT ... } class MainMenuOption : public Button { Q_OBJECT ... } 

When i do it

 MainMenuOption* messages = new MainMenuOption(); connect(messages, SIGNAL(selected()), SLOT(onMenuOptionSelected())) 

I will get the error:

QObject 'is the ambiguous base of' MainMenuOption '

The reason I admit NavigatableItem from QObject due to signals. Is there any way to do this?

Edit:

Adding virtual to each inheritance declaration still gives me the same error:

 class NavigatableItem : public virtual QObject class Button : public virtual NavigatableItem, public virtual QToolButton class MainMenuOption : public virtual Button 

Even after “clear everything”, “run qmake” and “build everything”.

+6
c ++ multiple-inheritance qt signals
source share
3 answers

This requires a bit more code, but what I have done in the past makes one of them (your NavigatableItem in this case) a pure virtual class, i.e. an interface. Instead of using the “signals” macro, make them pure virtual protected functions. Then multiply the inheritance from your class derived from QObject, as well as the interface, and implement the methods.

I know that this is somewhat controversial, but avoiding multiple inheritance of the implementation at any cost, it solves a lot of problems and confusion. Google C ++ style guides recommend this and I think this is good advice.

 class NavigatableItemInterface { // Don't forget the virtual destructor! protected: virtual void deselected() = 0; virtual void selected() = 0; virtual void activated() = 0; }; class Button : public NavigatableItemInterface, public QToolButton { Q_OBJECT ... signals: virtual void deselected(); ... } 
+8
source share

Use virtual inheritance like

 class X : public virtual Y { }; class Z : public virtual Y { }; class A : public virtual X, public virtual Z { }; 

will have only one copy of base class Y

+1
source share

You must use virtual inheritance.

see http://en.allexperts.com/q/C-1040/virtual-inheritance.htm

It looks like you are having a problem with a diamond, see also:

http://www.cprogramming.com/tutorial/virtual_inheritance.html

Do it like this:

 class NavigatableItem : public virtual QObject class Button : public virtual NavigatableItem, public virtual QToolButton class MainMenuOption : public Button 
0
source share

All Articles