graphicsView是 Qt 中用于显示和操作图形项的高级视图类。它与 QGraphicsScene 和 QGraphicsItem 一起构成了 Qt 的图形视图框架(Graphics View Framework)。这个框架允许你创建复杂的、可交互的 2D 图形场景,并提供了丰富的功能,如缩放、平移、选择、拖拽等。
此处实现一下缩放和平移。
缩放要重写wheelEvent事件
平移重写鼠标事件mousePressEvent
setDragMode(QGraphicsView::ScrollHandDrag);// 开启拖动模式
注意要在mouseMoveEvent
setDragMode(QGraphicsView::NoDrag);// 关闭拖动模式
下面的完整代码
class MyGraphicsView:public QGraphicsView
{
Q_OBJECT
public:
MyGraphicsView(QWidget* parent);
~MyGraphicsView();
protected:
// 鼠标左击
void mousePressEvent(QMouseEvent *event) override;
// 鼠标释放
void mouseReleaseEvent(QMouseEvent *event) override;
void wheelEvent(QWheelEvent *event) override;
};
void MyGraphicsView::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton&&isZoomEnabled) {
// 开启拖动模式
setDragMode(QGraphicsView::ScrollHandDrag);
}
//最后调用基类mouseMoveEvent函数,保留鼠标释放事件处理逻辑
QGraphicsView::mousePressEvent(event);
}
void MyGraphicsView::mouseReleaseEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
// 关闭拖动模式
setDragMode(QGraphicsView::NoDrag);
}
//最后调用基类mouseReleaseEvent函数,保留鼠标释放事件处理逻辑
QGraphicsView::mouseReleaseEvent(event);
}
void MyGraphicsView::wheelEvent(QWheelEvent *event)
{
// Get the current scale factor
double scaleFactor = 1.1; // Zoom in/out by 10% per wheel step
// Determine the direction of the zoom
if (event->angleDelta().y() > 0) {
// Zoom in
this->scale(scaleFactor, scaleFactor);
} else {
// Zoom out
this->scale(1.0 / scaleFactor, 1.0 / scaleFactor);
}
// Center the zoom at the mouse cursor position
QPointF mousePos = event->position();
QPointF scenePos = this->mapToScene(mousePos.toPoint());
this->centerOn(scenePos);
QGraphicsView::wheelEvent(event);
}