Search code examples
qtqgraphicsviewqgraphicssceneqmouseevent

graphicsview receives mouse event before the item


I have implemented the panning view on the QGraphicsView, using the mouse move event using

void View::mouseMoveEvent(QMouseEvent* event) {
pan();
QGraphicsView::mouseMoveEvent(event);
}

and in the scene of this view I have added few items where some of the items are resizable, so I implemented

void Item::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
 if(m_resizeMode)
    {
      resize();
      e->accept();
    }
}

I tried to filter the mouse move not to propagate to any further using e->accept() but my View mouseMove event has been called first , so when ever I tried to resize the item, the view started to pan all the way.

How can I avoid this event propagation from view to scene.


Solution

  • You can call the base class implementation of the QGraphicsView and check if the event is accepted. However I would do this in the mousePressEvent instead of the mouseMoveEvent. After all this is where you determine if you should resize an item or do some panning. This is how I do something similar in my project:

    void View::mousePressEvent(QMouseEvent *event)
    {
        ...
        QGraphicsView::mousePressEvent(event);
        if(event->isAccepted())
            move = false;
        else
            move = true;
    }
    
    void View::mouseMoveEvent(QMouseEvent *event)
    {
        if(!move)
        {
            QGraphicsView::mouseMoveEvent(event);
            return;
        }
        ... // you would do the panning here
    
        QGraphicsView::mouseMoveEvent(event);
    }
    
    void View::mouseReleaseEvent(QMouseEvent *event)
    {
        if(!move)
        {
            QGraphicsView::mouseReleaseEvent(event);
            return;
        }
        else
        {
            ...
            move = false;
        }
        QGraphicsView::mouseReleaseEvent(event);
    }