Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt: Proper Method to Implement Panning(Drag)

Tags:

c++

qt

QGraphicsview has a method setDragMode(ScrollHandDrag) to enable panning with the left mouse click. But I wanted to enable panning when the mouse wheel is clicked(the middle button) and created the following custom implementation to pan:

//Within a custom derived class of QGraphicsView
//pan is true when wheel is clicked and false when released
//last Pos is defined somewhere else in the class

void GridView::mouseMoveEvent(QMouseEvent *event){
     if(pan){
         QPointF currentPos = event->pos();
         QPointF relPos = currentPos - lastPos;
         lastPos = currentPos;

         //this is what creates the panning effect
         translate(relPos.x(), relPos.y());
     }
     QGraphicsView::mouseMoveEvent(event);
}

This works fine for the most part. But for example, if I scale the identity matrix by 1,000,000 this method fails and stops panning (as if the view got stuck). This problem doesn't arise when I use setDragMode()

What would be the proper custom implementation of setDragMode() so it is enabled by the wheel click?

like image 882
lambda Avatar asked Dec 26 '22 21:12

lambda


1 Answers

This works for me... it tricks Qt into thinking the user is pressing the left mouse button when he's really pressing the middle one.

void GridView :: mousePressEvent(QMouseEvent * e)
{
   if (e->button() == MidButton)
   {
      QMouseEvent fake(e->type(), e->pos(), LeftButton, LeftButton, e->modifiers());
      QGraphicsView::mousePressEvent(&fake);
   }
   else QGraphicsView::mousePressEvent(e);
}

void GridView :: mouseReleaseEvent(QMouseEvent * e)
{
   if (e->button() == MidButton)
   {
      QMouseEvent fake(e->type(), e->pos(), LeftButton, LeftButton, e->modifiers());
      QGraphicsView::mouseReleaseEvent(&fake);
   }
   else QGraphicsView::mouseReleaseEvent(e);
}
like image 53
Jeremy Friesner Avatar answered Dec 29 '22 05:12

Jeremy Friesner