I’ve subclassed QGraphicsItem into my own custom class, Hexagon. When I try to use a function such as QGraphicsView::itemAt, or QGraphicsScene::itemAt, it won’t return any of my Hexagon objects because the function instead looks for QGraphicsItems.
How can I tell it to look for Hexagon objects instead? Or do I need to change something in my Hexagon class? Or even re-implement itemAt()?
Currently, I’m also subclassing QGraphicsView, particlarly mousePressedEvent to get some info about the Hexagon object that is clicked on.
void LatticeView::mousePressEvent(QMouseEvent *event)
{
Hexagon *hexagon = itemAt(event->pos());
...
}
But when I try to compile, I get the following error:
invalid conversion from ‘QGraphicsItem*’ to ‘Hexagon*’
What I want is to be able to get the Hexagon object that is clicked on so that I can access some variables I’ve defined in the Hexagon class that are not implicit in the QGraphicsItem class.
To get this to work, you would need to cast the pointer before assigning it to a pointer variable of another type..
But there is danger here since
itemAt()may returnNULLor the item may not be aHexagonitem.In fact, you should use the C++ style cast like this:
This will require Run-time type information to be available through your compiler.
There is also a
QGraphicsItemfunction available called type() which will allow you to useqgraphicsitem_cast()but that requires a little extra work involving defining anenum.One additional thing to watch out for. Depending on how your scene and items are consuming mouse events, you may not always see your override of
mousePressEvent()get called when you expect it to since the mouse event may never get up to the view if it is consumed by something in the scene.