4

QGraphicsview 有一个方法setDragMode(ScrollHandDrag)可以用鼠标左键点击平移。但是我想在单击鼠标滚轮(中间按钮)时启用平移并创建以下自定义实现来平移:

//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);
}

这在大多数情况下都可以正常工作。但例如,如果我将单位矩阵缩放 1,000,000,此方法将失败并停止平移(好像视图卡住了)。我使用时不会出现此问题setDragMode()

什么是正确的自定义实现,setDragMode()所以它是由滚轮点击启用的?

4

1 回答 1

10

这对我有用...它欺骗 Qt 认为用户在按下鼠标左键时实际上是在按下鼠标左键。

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);
}
于 2013-09-01T00:50:31.240 回答