1. 继承QGraphicsView;
class MyGraphicsView : public QGraphicsView
2. 重写构造函数
MyGraphicsView(QGraphicsScene *scene, QWidget *parent = 0);
3.设置 scene 尺寸
scene->setSceneRect(0, 0, 1280, 720);
4. 重写paintEvent 函数,在其中设置世界坐标变换和缩放
QPainter painter(viewport());
painter.setWorldTransform(this->viewportTransform(), true);
painter.scale(m_zoomLevel, m_zoomLevel);
5. 重写 wheelEvent 函数,
void QGraphicsView::wheelEvent(QWheelEvent* event)
{
if (QApplication::keyboardModifiers() == Qt::ControlModifier) {
qreal rate = event->delta() / 1200.00;
m_zoomLevel += rate;
updateZoomLevel(m_zoomLevel);
}
QGraphicsView::wheelEvent(event);
}
void MyGraphicsView::updateZoomLevel(qreal zoom)
{
if (zoom >= 0.1 && zoom <= 9.99)
m_zoomLevel = zoom;
else if (zoom < 0.1)
m_zoomLevel = 0.1;
else
m_zoomLevel = 9.99;
int x = (width() - width() * zoom) * 0.5;
int y = (height() - height() * zoom) * 0.5;
scene()->setSceneRect(x, y, width() * zoom - 4, height() * zoom - 4);
viewport()->update();
}
QGraphicsView 的重绘,用viewport()->update(); 直接调update是调用view 的刷新,而不是scene的刷新。