Search code examples
c++qtqgraphicsviewqgraphicsitem

Confused by doubleclickevent and mousepressevent in Qt


The situation is:

In side a QGraphicsView, I used its doubleClickEvent function to create a QGraphicsItem. I rewrite the QGraphicsItem's mousePressEvent function to simply print a qDebug information.

However, what I found is that: even if I just double click to create that QGraphicsItem, the newly created QGraphicsItem's mousePressEvent is also called.

How would this happen? What can I do to prevent this?


Solution

  • A QGraphicsView is a widget, so it has a doubleClickEvent. In contrast, a QGraphicsItem is not a widget, but has a mousePressEvent.

    When you override events, if you don't want them to be propagated to other objects, you need to accept the event to tell the system that you've handled it.

    void MyGraphicsView::mouseDoubleClickEvent(QMouseEvent * event)
    {
       // Create a graphics item..
       ...
       event->accept(); // tell the system that the event has been handled
    }
    

    Without accepting the event, the double click is passed on to the QGraphicsScene and then QGraphicsItem.

    If you want to be able to double-click to create an item when clicking on an empty area of a scene, but have an item react if you double-click on an item, you can override the scene's mouseDoubleClickEvent instead of the view and check if there's an item at the cursor position before deciding upon whether or not to create an item, or pass the event on.

    void QGraphicsScene::mouseDoubleClickEvent( QGraphicsSceneMouseEvent * mouseEvent )
    {
        if(items(mouseEvent->scenePos()).isEmpty()) // if no items are at this position
        {
             // create new graphics item
             ...
             mouseEvent->accept(); // don't propagate the event
        }
    
        // no items, so allow the event to propagate by doing nothing
    }