I have a class (MyClass
) that inherits most of its functionality from a Qt built-in object (QGraphicsTextItem
). QGraphicsTextItem
inherits indirectly from QObject
. MyClass
also implements an interface, MyInterface
.
class MyClass : public QGraphicsTextItem, public MyInterface
I need to be able to use connect
and disconnect
on MyInterface*
. But it appears that connect
and disconnect
only work on QObject*
instances. Since Qt does not support multiple inheritance from QObject-derived classes, I cannot derive MyInterface
from QObject
. (Nor would that make much sense for an interface anyway.)
There is a discussion of the problem online, but IMO the proposed solution is fairly useless in the common case (accessing an object through its interface), because you cannot connect the signals and slots from MyInterface*
but must cast it to the derived-type. Since MyClass
is one of many MyInterface
-derived classes, this would necessitate "code-smelly" if-this-cast-to-this-else-if-that-cast-to-that statements and defeats the purpose of the interface.
Is there a good solution to this limitation?
UPDATE: I noticed that if I dynamic_cast
a MyInterface*
to QObject*
(because I know all MyInterface
-derived classes also inherit eventually from QObject
, it seems to work. That is:
MyInterface *my_interface_instance = GetInstance();
connect(dynamic_cast<QObject*>(my_interface_instance), SIGNAL(MyInterfaceSignal()), this, SLOT(TempSlot()));
But this really seems like I am asking for undefined behavior....