Time for action – implementing the ability to move the scene
Next it would be good to move the scene around without the need of using the scroll bars. Let us add the functionality for pressing and holding the left mouse button. First, we add two private members to the view: the m_pressed
parameter of type bool
and the m_lastMousePos
element of type QPoint
. Then, we reimplement the mousePressEvent()
and mouseReleaseEvent()
functions as follows:
void MyView::mousePressEvent(QMouseEvent *event) { if (Qt::LeftButton == event->button()) { m_pressed = true; m_lastMousePos = event->pos(); } QGraphicsView::mousePressEvent(event); } void MyView::mouseReleaseEvent(QMouseEvent *event) { if (Qt::LeftButton == event->button()) m_pressed = false; QGraphicsView::mouseReleaseEvent(event); }
What just happened?
Within mousePressEvent()
, we check whether the left mouse button was pressed. If it was true
, we then set m_pressed
to true
and save the current mouse position in m_lastMousePos...