1

I have derived from both QGraphicsView and QGraphicsRectItem. I overloaded the contextMenuEvent on both classes to provide popup menus. I want the QGraphicsView context menu when you click on white space the the QGraphicsItem popup menu when you click on an item.

At first implementation, I got the QGraphicsView popup no matter where I clicked. So I modified the contextMenuEvent as follows:

void CustomGraphicsView::contextMenuEvent(QContextMenuEvent* event)
{
  if (QGraphicsItem *item = itemAt(event->pos())) {
    MyRect* rect = dynamic_cast<MyRect*>(item);
    QGraphicsSceneContextMenuEvent* context_event = dynamic_cast<QGraphicsSceneContextMenuEvent*>(event);
    if (rect && context_event)
      rect->contextMenuEvent(context_event);
  }
  else {
    QMenu menu;
     ... create the QGraphicsView popup menu
  }
}

The dynamic_cast for the QGraphicsSceneContextMenuEvent fails so I never call the contextMenuEvent for the rect. It won't compile if I just try to pass the event to the rect->contextMenu(), so I tried the cast.

What is the right way to do this?

This is a learning project to just create/move/rotate/delete 2D shapes using Qt. If someone wants to look at the whole thing, let me know.

cagem12
  • 43
  • 5
  • http://www.cplusplus.com/doc/tutorial/typecasting/#dynamic_cast says "dynamic_cast can only be used with pointers and references to classes (or with void*)." It might be worth a read. –  Jul 30 '16 at 15:53
  • You already answered to your question, but also look at [`qgraphicsitem_cast`](http://doc.qt.io/qt-5/qgraphicsitem.html#qgraphicsitem_cast), for the future. – ilotXXI Jul 30 '16 at 19:49
  • Thanks for the tip. That is one that I didn't know about. – cagem12 Jul 30 '16 at 22:00

1 Answers1

0

OK, so I figured it out. Just make sure to pass the event through the base class method. Simple! This also works for the mousePressEvent(), mouseMoveEvent(), and mouseReleaseEvent functions.

void CustomGraphicsView::contextMenuEvent(QContextMenuEvent* event)
{
  // if the event is on a GGraphicsItem just pass the event along
  if (itemAt(event->pos())) {
    QGraphicsView::contextMenuEvent(event);
  }
  else
  {
    QMenu menu;
    ... create popup for the CustomGraphicsView
cagem12
  • 43
  • 5