项目场景:
创建一个QGraphicsView和QGraphicsScene,实现中键移动缩放
移动代码实现
实现方法:移动鼠标时改变滚动条的值
void GraphicsView::mousePressEvent(QMouseEvent* event)
{
if (event->button() == Qt::MiddleButton)
{
midButtonPressed = event->pos();
}
else
{
QGraphicsView::mousePressEvent(event);
}
}
void GraphicsView::mouseMoveEvent(QMouseEvent* event)
{
if (event->buttons() & Qt::MiddleButton)
{
auto offset = event->pos() - midButtonPressed;
// scrollContentsBy(offset.x(), offset.y()); //错误代码
verticalScrollBar()->setValue(verticalScrollBar()->value() - offset.y());
horizontalScrollBar()->setValue(horizontalScrollBar()->value() - offset.x());
midButtonPressed = event->pos();
}
else
{
QGraphicsView::mouseMoveEvent(event);
}
}
缩放代码实现:
实现方法:通过QGraphicsView::scale()进行缩放
void GraphicsView::wheelEvent(QWheelEvent* event)
{
if (event->angleDelta().y() > 0) //forward
{
m_scale = qMax(m_scale, 1.0); //reset to 1 if m_scale < 1
m_scale += 0.05;
if (transform().m11() > 2)
m_scale = 1;
}
else if (event->angleDelta().y() < 0) //backward
{
m_scale = qMin(m_scale, 1.0); //reset to 1 if m_scale > 1
m_scale -= 0.05;
if (transform().m11() < 0.3)
m_scale = 1;
}
scale(m_scale, m_scale);
}
错误提示:
1. QGraphicsView提供了scrollContentsBy(int dx, int dy)
的方法可以移动内容,但是在调用该方法移动并进行缩放会发现移动重置,查阅文档如下,应当修改为移动滚动条的值来移动
Calling this function in order to scroll programmatically is an error,
use the scroll bars instead (e.g. by calling QScrollBar::setValue() directly).