Using Qt signals and slots with multiple inheritance

被刻印的时光 ゝ 提交于 2019-11-30 13:10:29

You found the answer yourself: the dynamic_cast works as you would expect. It is not undefined behavior. If the instance of MyInterface you got is not a QObject, the cast will return null and you can guard yourself against that (which won't happen, since you said all instances of the interface are also QObjects). Remember, however, that you need RTTI turned on for it to work.

I would also offer a few other suggestions:

  • Use the Q_INTERFACES feature (it's not only for plug-ins). Then you'd work in terms of QObject and query for MyInterface using qobject_cast when it is really needed. I don't know your problem in detail, but since you know that all MyInterface instances are also QObjects, this seems to be the most sensible approach.

  • Add a QObject* asQObject() abstract method to MyInterface and implement it as { return this; } in all subclasses.

  • Having a QGraphicsTextItem (composition) instead of being one (inheritance).

You can declare MyInterface that takes a QObject in its constructor:

class MyInterface {
public:
                MyInterface(QObject * object);
    QObject *   object() { return m_object; }
    ...
private:
    QObject *   m_object;
};

MyInterface::MyInterface(QObject * object) :
    m_object(object)
{
    ...
}

Then in MyClass constructor:

MyClass::MyClass() :
MyInterface(this)
{
    ...
}

And you can connect the signal:

MyInterface *my_interface_instance = GetInstance();
connect(my_interface_instance->object(), SIGNAL(MyInterfaceSignal()), this, SLOT(TempSlot()));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!