子类QGraphicsItem使我无法在QGraphicsScene/View上使用itemAt()

Subclassing QGraphicsItem prevents me from being able to use itemAt() on a QGraphicsScene/View

本文关键字:View itemAt QGraphicsScene QGraphicsItem 子类      更新时间:2023-10-16

我已经将QGraphicsItem子类化为我自己的自定义类Hexagon。当我尝试使用QGraphicsView::itemAtQGraphicsScene::itemAt之类的函数时,它不会返回任何Hexagon对象,因为该函数会查找QGraphicsItems
如何告诉它查找Hexagon对象?还是我需要更改Hexagon类中的某些内容?甚至重新实施itemAt()

目前,我还在对QGraphicsView,特别是mousePressedEvent进行子类化,以获得有关单击的Hexagon对象的一些信息

void LatticeView::mousePressEvent(QMouseEvent *event)
{
    Hexagon *hexagon = itemAt(event->pos());
    ...
}

但当我尝试编译时,我会得到以下错误:

从"QGraphicsItem*"到"Hexagon*"的转换无效

我想要的是能够获得被点击的Hexagon对象,这样我就可以访问我在Hexagon类中定义的一些在QGraphicsItem类中不隐含的变量。

要实现这一点,您需要先强制转换指针,然后再将其分配给另一种类型的指针变量。。

Hexagon *hexagon = (Hexagon*)itemAt(event->pos());

但是这里存在危险,因为itemAt()可能返回NULL或者该项目可能不是Hexagon项目。

事实上,您应该像这样使用C++样式的转换:

Hexagon *hexagon = dynamic_cast<Hexagon*>(itemAt(event->pos()));
if (hexagon != NULL)
{
   hexagon->hexagonMethod();
}

这需要通过编译器获得运行时类型信息。

还有一个名为type()的QGraphicsItem函数,它将允许您使用qgraphicsitem_cast(),但这需要一些额外的工作,包括定义enum

还有一件事需要注意。根据场景和项目使用鼠标事件的方式,您可能不会总是看到mousePressEvent()的覆盖在您期望的时候被调用,因为如果鼠标事件被场景中的某个东西使用,它可能永远不会到达视图。