QT: trouble with qobject_cast
我派生了QGraphicsItem和QGraphicsScene类。我希望项目能够调用scene()并获得derviedGraphicsItem *而不是QGraphicsItem *,因此我重新实现了QGraphicsScene :: itemAt以返回派生的指针。
1 2 3 4 5 | DerivedItem* DerivedScene::itemAt( const QPointF &position, const QTransform &dt ) const { return qobject_cast< DerivedItem * >( QGraphicsScene::itemAt(position, dt) ); } |
我收到以下错误(Qt 4.6,Ubuntu 10.4上的GCC 4.4.3)
1 2 | scene.cpp: In member function ‘DerivedItem* DerivedScene::itemAt(qreal, qreal, const QTransform&) const’: scene.cpp:28: error: no matching function for call to ‘qobject_cast(QGraphicsItem*)’ |
然后我注意到QGraphicsItem不继承QObject,所以我使派生的QGraphicsItem类具有从QObject和QGraphicsItem的多重继承,并且在添加Q_OBJECT宏并重建项目后,我得到了相同的错误。
我会以错误的方式处理吗?我知道尝试将父类强制转换为子类应该是一个糟糕的设计,但是在这种情况下,这似乎是我想要的,因为我的派生项目类具有新功能,并且其对象需要一种在其上调用该新功能的方式周围的物品,并用itemAt()询问物品场景对象似乎是最好的方法-但我需要itemAt()返回正确类型的指针。我可以通过使用Dynamic_cast使派生项强制转换为QGraphicsScene :: itemAt()返回的QGraphicsItem *来解决此问题,但我并不真正理解为什么它起作用而不是qobject_cast,或者不知道使用dynamic_cast与qobject_cast的利弊。
编辑:
忘了提一下,我还在派生类中重新实现了QGraphicsItem :: scene(),以返回DerivedScene *,如下
1 2 3 4 | DerivedScene* DerivedItem::scene() const { return qobject_cast< DerivedScene * >( QGraphicsItem::scene() ); } |
但这似乎没有引起编译错误...
从QObject继承仅用于铸造是没有意义的。 qobject_cast的优点
qobject_cast文档中对动态转换进行了总结:
The qobject_cast() function behaves similarly to the standard C++ dynamic_cast(), with the advantages that it doesn't require RTTI support and it works across dynamic library boundaries.
如果您拥有QObject,那么拥有它会很好,而且很有用;但是,如果您想从QObject中获得它,那么就不值得从QObject继承。
此外,对于QGraphicsIems,还有qgraphicsitem_cast,它应该完全按照您的要求进行:)
您必须将QObject指针传递给qobject_cast(),并且QGraphicsScene :: itemAt返回QGraphicsItem指针。 正如您提到的,由于QGraphicsItem不是从QObject派生的,因此编译器给您带来了该错误。