使用鼠标滚轮缩放 QChartView 的 x 轴

Scale x-axis of QChartView using mouse wheel

在我的应用程序中,我使用 QChart 来显示折线图。不幸的是,Qt Charts 不支持使用鼠标滚轮缩放和通过鼠标滚动等基本功能。是的,有 RubberBand 功能,但仍然不支持滚动等,这对用户来说不是那么直观。此外,我只需要缩放 x 轴,某种 setRubberBand(QChartView::HorizontalRubberBand) 但使用鼠标滚轮。 到目前为止,在深入 QChartView 之后,我使用了以下解决方法:

class ChartView : public QChartView {
protected:
    void wheelEvent(QWheelEvent *event) Q_DECL_OVERRIDE
    {
        QRectF rect = chart()->plotArea();            
        if(event->angleDelta().y() > 0)
        {
            rect.setX(rect.x() + rect.width() / 4);
            rect.setWidth(rect.width() / 2);                                   
        }
        else
        {
            qreal adjustment = rect.width() / 2;
            rect.adjust(-adjustment, 0, adjustment, 0);                    
        }            
        chart()->zoomIn(rect);
        event->accept();            
        QChartView::wheelEvent(event);
    }
}

这行得通,但放大然后缩小不会导致相同的结果。有一个小偏差。调试后我发现 chart()->plotArea() 总是 returns 相同的矩形,所以这个解决方法是无用的。

有没有办法只获取可见区域的矩形? 或者有人可以指出正确的解决方案如何通过鼠标为 QChartView 做 zooming/scrolling?

您可以使用 zoom() 而不是 zoomIn()zoomOut(),如下所示:

class ChartView : public QChartView {
protected:
    void wheelEvent(QWheelEvent *event) Q_DECL_OVERRIDE
    {
        qreal factor = event->angleDelta().y() > 0? 0.5: 2.0;
        chart()->zoom(factor);
        event->accept();
        QChartView::wheelEvent(event);
    }
};

关于zoomIn()zoomOut(),具体指的是什么坐标还不清楚,我还在投资中,等我有更多信息再更新我的回答。

更新:

据我观察,其中一个问题是浮点数的乘法,另一个是定位图形的中心,为了不出现这些问题,我的解决方案是重置缩放,然后设置更改:

class ChartView : public QChartView {
    qreal mFactor=1.0;
protected:
    void wheelEvent(QWheelEvent *event) Q_DECL_OVERRIDE
    {
        chart()->zoomReset();

        mFactor *= event->angleDelta().y() > 0 ? 0.5 : 2;

        QRectF rect = chart()->plotArea();
        QPointF c = chart()->plotArea().center();
        rect.setWidth(mFactor*rect.width());
        rect.moveCenter(c);
        chart()->zoomIn(rect);

        QChartView::wheelEvent(event);
    }
};

我使用以下代码实现了 x 和 y 缩放:

void wheelEvent(QWheelEvent *event){
qreal factor;
if ( event->delta() > 0 )
    factor = 2.0;
else
    factor = 0.5;

QRectF r = QRectF(chart()->plotArea().left(),chart()->plotArea().top(),
                                    chart()->plotArea().width()/factor,chart()->plotArea().height()/factor);
QPointF mousePos = mapFromGlobal(QCursor::pos());
r.moveCenter(mousePos);
chart()->zoomIn(r);
QPointF delta = chart()->plotArea().center() -mousePos;
chart()->scroll(delta.x(),-delta.y());}