缩放QGrahicsView时,mousewheentturn首先滚动,然后缩放

Scaling a QGrahicsView when MouseWheenTurned first scrolls, then scales

本文关键字:缩放 滚动 然后 mousewheentturn QGrahicsView      更新时间:2023-10-16

我试图添加放大/缩小功能到我在Qt绘图的图形。我首先做的是扩展QGraphicsScene与我自己的类GraphicsScene和重载车轮事件。

class GraphicsScene : public QGraphicsScene
{
    Q_OBJECT
public:
    GraphicsScene(QObject *parent, bool drawAxes){ /*drawing stuff here.. */}
    virtual void wheelEvent(QGraphicsSceneWheelEvent *mouseEvent);   
signals:
    void mouseWheelTurned(int);
};

void GraphicsScene::wheelEvent(QGraphicsSceneWheelEvent* mouseEvent) {
  int numDegrees = mouseEvent->delta() / 8;
  int numSteps = numDegrees / 15; // see QWheelEvent documentation
  emit mouseWheelTurned(numSteps);
}

当车轮转动时,一个事件被发送到包含场景的视图,并在那里执行缩放:

class GraphicsView : public QGraphicsView{
    Q_OBJECT
    qreal m_currentScale;
public:
GraphicsView(QWidget * parent): QGraphicsView(parent){  m_currentScale = 1.0; }
public slots:
    void            onMouseWheelTurned  (int);
};
void GraphicsView::onMouseWheelTurned(int steps) {
    qreal sign = steps>0?1:-1;
    qreal current = sign* pow(0.05, abs(steps));
    if(m_currentScale+current > 0){
        m_currentScale += current;
        QMatrix matrix;
        matrix.scale(m_currentScale, m_currentScale);
        this->setMatrix(matrix);
    }
}

这是有效的,但我注意到,如果我放大很多,例如到图形的顶部,那么图形不再完全在视口中,然后我缩小,程序首先滚动到图形的底部。我可以看到垂直滚动条向下滑动。只有当它到达底部时,它才开始缩小。有什么问题吗?

我想在没有上下滚动的情况下放大/缩小

你最好在场景中处理这个问题,并向视图发送一个事件。

直接在视图中使用QGraphicsView::wheelEvent}处理事件,然后调用其缩放函数