问题描述
我有一个问题QT关于多个继承,因为QObject。我知道很多其他人有相同的问题,但我不知道我该如何解决它。
I'm having a problem with QT regarding multiple enheritance because of QObject. I know that a lot of others have the same problems but I don't know how I should 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
...
}
当我这样做
MainMenuOption* messages = new MainMenuOption();
connect(messages, SIGNAL(selected()), SLOT(onMenuOptionSelected()))
我会得到错误:
为什么我让NavigatableItem从QObject继承的原因是因为信号。有办法吗?
The reason why I let NavigatableItem enherit from QObject because of the signals. Is there a way to do this?
编辑:
每个继承声明,仍然给我相同的错误:
Adding virtual to each inheritence 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
即使在清除所有,运行qmake和构建所有之后。
Even after a 'clean all', 'run qmake' and 'build all'.
推荐答案
代码,但我过去做的是使其中一个(你的 NavigatableItem
在这种情况下)一个纯虚拟类,即接口。而不是使用信号宏,使它们是纯虚拟保护函数。然后从你的QObject派生类和接口乘法继承,并实现方法。
It requires a bit more code, but what I have done in the past is make one of them (your NavigatableItem
in this case) a pure virtual class, i.e. interface. Instead of using the "signals" macro, make them pure virtual protected functions. Then multiply-inherit from your QObject-derived class as well as the interface, and implement the methods.
我知道这是有点争议,但避免多重实现继承成本确实解决了大量的问题和混乱。 推荐了这一点,我认为这是个好建议。 p>
I know it is somewhat controversial, but avoiding multiple implementation inheritance at all costs does solve a host of problems and confusion. The Google C++ Style Guidelines recommend this, and I think it 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();
...
}
这篇关于Qt多重继承和信号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!