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()
的正确自定义实现是什么,所以通过滚轮点击启用它?
答案 0 :(得分:10)
这对我有用......当Qt真正按下中间按钮时,它会让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);
}