2
votes

I have a View class which is reimplemented from the QGraphicsView class.

I'm trying to draw a line when the mouse is clicked with right button.

Here is my mousePressEvent, mouseReleaseEvent and mouseMoveEvent codes :


View::View(QWidget *parent) :  QGraphicsView(parent)
{
    setAcceptDrops(true);
    setDragMode(QGraphicsView::RubberBandDrag);
    posFirst = QPoint(0,0);
    setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);
    pressed = false;
    area = new Area;
    setScene(area);
    selectionLine = new QGraphicsLineItem(0,0,0,0,0,area);
    selectionLine->setPen(QPen(Qt::DashLine));
}

void View::mousePressEvent(QMouseEvent *event){ if(event->button() == Qt::RightButton ){ posFirst.setX( event->pos().x() ); posFirst.setY( event->pos().y() ); pressed = true; selectionLine->setVisible(true); } QGraphicsView::mousePressEvent(event); }

void View::mouseReleaseEvent(QMouseEvent *event){ update(); pressed = false; selectionLine->setVisible(false); event->accept(); selectionLine->setLine(0,0,0,0); QGraphicsView::mouseReleaseEvent(event); }

void View::mouseMoveEvent(QMouseEvent *event){ if(pressed ){ selectionLine->setLine(posFirst.x() , posFirst.y() , event->pos().x() , event->pos().y() ); } QGraphicsView::mouseMoveEvent(event); }

But this code does not work properly. It doesn't catch mouse relase events and mouse move events properly. If I set if(event->button() == Qt::LeftButton ) then it works as expected.

Also I tried with Qt::MidButton and it worked.

What is the problem with RightButton ?

1

1 Answers

3
votes

I think that the problem is in the viewport of the graphics view. QGraphicsView renders the scene on the viewport, which is also a QWidget (it might be an OpenGL viewport, or something else). So this viewport catches and handles all the events.

You are better off to watch for the mouse press events on the scene, not on the view. The view displays only a potion of the scene, you will have to translate the view coords into the scene coords in order to properly create a line.

I also like to avoid subclassing the scene/view, instead create a manager object that is registered as an event filter on the scene with QObject::installEventFilter. This way you can plug in different managers into different scenes and not bother with inheritance.