QT5 QCustomPlot实现动态曲线绘制,可以左键放大、右键拖拽、跟随鼠标显示坐标

QT5 QCustomPlot实现动态曲线绘制

1.准备

  1. 下载文件,官网:https://www.qcustomplot.com/
  2. 按照官网教程,qt添加帮助文件。
  3. git或github下载:XCustomPlot
  4. 打开项目,将1下载的文件解压,添加qcustomplot.cpp/p。
  5. 在pro文件中添加QT += widgets printsupport、添加CONFIG += c++11.
  6. 引入头文件 #include “qcustomplot.h”
  7. 在ui中添加Widgeet,提升为QCustomPlot;
  8. 编译。

2.鼠标矩形框进行框选放大、右键平移

可参考:https://blog.youkuaiyun.com/qq_31073871/article/details/90108646

1.在QCustomPlot类中添加private变量:

private:
  QRubberBand *rb;
  QPoint startPos;
  bool cancelRb;
  1. 直接在h文件中,QCustomPlot类中添加ESC按键处理函数
virtual void QCustomPlot::keyPressEvent(QKeyEvent *e)
{
    if(e->key() == Qt::Key_Escape) {
        cancelRb = true; //记录标志位,以便释放鼠标后不执行缩放代码
        rb->hide();//隐藏选择框
    }
}
  1. 在QCustomPlot的3个鼠标事件函数添加代码

0、在构造函数QCustomPlot::QCustomPlot(QWidget *parent)的初始化列表中添加:
  ,rb(new QRubberBand(QRubberBand::Rectangle, this))
  ,startPos(0, 0)
1、左键按下时,记录坐标起点
    在QCustomPlot::mousePressEvent(QMouseEvent *event)中添加:
    if(event->buttons() & Qt::LeftButton)
    {
        startPos = event->pos();
        cancelRb = false;
        rb->resize(0, 0);
        rb->show();
    }
 
2、左键按下并移动时,绘制矩形框
    在void QCustomPlot::mouseMoveEvent(QMouseEvent *event)中添加:
 
    if(event->buttons() & Qt::LeftButton)
    {
        QRect normalRect = QRect(startPos, event->pos()).normalized();//任意两点定义矩形
        rb->setGeometry(normalRect);
    }
3、左键弹起时,记录终点坐标,并把曲线放大到【起点、终点】围成的矩形框中
    在void QCustomPlot::mouseReleaseEvent(QMouseEvent *event)中添加:
 
    if(event->button() == Qt::LeftButton)
    {
        rb->hide();
        if(!cancelRb)
        {
            QRect normalRect = QRect(startPos, event->pos()).normalized();
            rb->setGeometry(normalRect);
            this->xAxis->setRange(xAxis->pixelToCoord(normalRect.left()),
                                  xAxis->pixelToCoord(normalRect.right()));
 
            this->yAxis->setRange(yAxis->pixelToCoord(normalRect.bottom()),
                                  yAxis->pixelToCoord(normalRect.top()));
            this->replot();//立即刷新图像
        }
    }
  1. 在void QCPAxisRect::mousePressEvent(QMouseEvent *event, const QVariant &details),内部改为右键
  if ((event->buttons() & Qt::RightButton) || (event->buttons() & Qt::MiddleButton))

3.最终效果

演示

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值