我已经派生了QGraphicsItem和QGraphicsScene类。我希望项目能够调用scene()方法并获取derivedGraphicsItem *而不是QGraphicsItem *,因此我重新实现了QGraphicsScene::itemAt以返回一个派生指针。
DerivedItem* DerivedScene::itemAt( const QPointF &position, const QTransform &dt ) const
{
return qobject_cast< DerivedItem * >(
QGraphicsScene::itemAt(position, dt) );
}
我在Ubuntu 10.4上使用Qt 4.6和GCC 4.4.3时遇到了以下错误:
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 *进行强制转换来解决此问题,但我真的不理解为什么dynamic_cast可以而qobject_cast不行,或者使用dynamic_cast与qobject_cast的优缺点。
编辑:我忘记提及我还在我的派生类中重新实现了QGraphicsItem :: scene()以返回DerivedScene *。
DerivedScene* DerivedItem::scene() const
{
return qobject_cast< DerivedScene * >( QGraphicsItem::scene() );
}
但是这似乎并没有引起编译错误...