Using Qt signals and slots with multiple inheritance

前端 未结 2 611
野的像风
野的像风 2021-01-02 09:52

I have a class (MyClass) that inherits most of its functionality from a Qt built-in object (QGraphicsTextItem). QGraphicsTextItem inhe

2条回答
  •  春和景丽
    2021-01-02 10:21

    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).

提交回复
热议问题