QChart 表格 平移 + 缩放

穿精又带淫゛_ 提交于 2020-01-29 05:32:23

效果:
在这里插入图片描述

.h

#ifndef QTCHARTDEMOZOOM_H_38020FA5_FC74_4395_A807_61BF924D2F06
#define QTCHARTDEMOZOOM_H_38020FA5_FC74_4395_A807_61BF924D2F06

#include <QtCharts/QChartView>

using namespace QtCharts;

class QtChartDemoZoom : public QChartView
{
    Q_OBJECT
public:
    QtChartDemoZoom(QWidget* pParent = nullptr);
    ~QtChartDemoZoom();

protected:
    virtual void mouseMoveEvent(QMouseEvent *pEvent) override;
    virtual void mousePressEvent(QMouseEvent *pEvent) override;
    virtual void mouseReleaseEvent(QMouseEvent *pEvent) override;
    virtual void wheelEvent(QWheelEvent *pEvent) override;

private:
    bool m_bMiddleButtonPressed;
    QPoint m_oPrePos;
};
#endif //QTCHARTDEMOZOOM_H_38020FA5_FC74_4395_A807_61BF924D2F06

.cpp

#include <QLineSeries>

QtChartDemoZoom::QtChartDemoZoom(QWidget* pParent /*= nullptr*/)
    : QChartView(pParent)
    , m_bMiddleButtonPressed(false)
    , m_oPrePos(0, 0)
{
    QLineSeries *pLineServies = new QLineSeries();
    for (int i = 0; i < 100; ++i)
    {
        pLineServies->append(i, qrand() % 10);
    }
    this->chart()->addSeries(pLineServies);
    this->chart()->createDefaultAxes();
}

 QtChartDemoZoom::~QtChartDemoZoom()
{

}

void QtChartDemoZoom::mouseMoveEvent(QMouseEvent *pEvent)
{
    if (m_bMiddleButtonPressed)
    {
        QPoint oDeltaPos = pEvent->pos() - m_oPrePos;
        chart()->scroll(-oDeltaPos.x(), oDeltaPos.y());
        m_oPrePos = pEvent->pos();
    }
    __super::mouseMoveEvent(pEvent);
}

void QtChartDemoZoom::mousePressEvent(QMouseEvent *pEvent)
{
    if (pEvent->button() == Qt::MiddleButton)
    {
        m_bMiddleButtonPressed = true;
        m_oPrePos = pEvent->pos();
        this->setCursor(Qt::OpenHandCursor);
    }
    __super::mousePressEvent(pEvent);
}

void QtChartDemoZoom::mouseReleaseEvent(QMouseEvent *pEvent)
{
    if (pEvent->button() == Qt::MiddleButton)
    {
        m_bMiddleButtonPressed = false;
        this->setCursor(Qt::ArrowCursor);
    }
    __super::mouseReleaseEvent(pEvent);
}

void QtChartDemoZoom::wheelEvent(QWheelEvent *pEvent)
{
    qreal rVal = std::pow(0.999, pEvent->delta()); // 设置比例
    // 1. 读取视图基本信息
    QRectF oPlotAreaRect = chart()->plotArea();
    QPointF oCenterPoint = oPlotAreaRect.center();
    // 2. 水平调整
    oPlotAreaRect.setWidth(oPlotAreaRect.width() * rVal);
    // 3. 竖直调整
    oPlotAreaRect.setHeight(oPlotAreaRect.height() * rVal);
    // 4.1 计算视点,视点不变,围绕中心缩放
    //QPointF oNewCenterPoint(oCenterPoint);
    // 4.1 计算视点,让鼠标点击的位置移动到窗口中心
    //QPointF oNewCenterPoint(pEvent->pos());
    // 4.2 计算视点,让鼠标点击的位置尽量保持不动(等比换算,存在一点误差)
    QPointF oNewCenterPoint(2 * oCenterPoint - pEvent->pos() - (oCenterPoint - pEvent->pos()) / rVal);
    // 5. 设置视点
    oPlotAreaRect.moveCenter(oNewCenterPoint);
    // 6. 提交缩放调整
    this->chart()->zoomIn(oPlotAreaRect);

    __super::wheelEvent(pEvent);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!