QcustomPlot 多条单条曲线光标自动更随的实现

QcustomPlot 多条单条曲线光标自动更随的实现QcustomPlot光标跟随最近有一个需求是能绘制多条曲线且能光标跟随,上网搜了很多相关的资料,如下边这个博客中查到了鼠标更随的相关代码,他的图如下所示——[原文链接地址](https://blog.csdn.net/sunnyloves/article/details/82344815)还有一篇如下所示——[原文链接地址](https://www.cnblogs.com…


Jetbrains全系列IDE稳定放心使用

QcustomPlot光标跟随

最近有一个需求是能绘制多条曲线且能光标跟随,上网搜了很多相关的资料,如下边这个博客中查到了鼠标更随的相关代码,他的图如下所示——原文链接


QcustomPlot 多条单条曲线光标自动更随的实现

还有一篇如下所示——原文链接


QcustomPlot 多条单条曲线光标自动更随的实现

第一篇博主的实现方法其实已经比较完善了但是我按照他的方法去做后构造函数有点问题,所以对其做了一些修改之后得到如下结果——


QcustomPlot 多条单条曲线光标自动更随的实现
三条每条100万数据点曲线实时追踪无延迟,边界跳0无数据,本文所用为QcustomPlot2.0.1。 首先说的是对上边所提第一篇博客做的修改,代码如下

#ifndef MYTRACER_H
#define MYTRACER_H

#include <QObject>
#include "qcustomplot.h"
enum TracerType
{ 
   
    XAxisTracer,
    YAxisTracer,
    DataTracer
};

class myTracer : public QObject
{ 
   
    Q_OBJECT
public:



public:
    explicit myTracer(QCustomPlot *_plot,QCPGraph *_graph, TracerType _type);//这里与原贴不同,按照原贴构造总是过不去
    ~myTracer();

    void setPen(const QPen &pen);
    void setBrush(const QBrush &brush);
    void setText(const QString &text);
    void setLabelPen(const QPen &pen);
    void updatePosition(double xValue, double yValue);

protected:
    void setVisible(bool visible);
protected:
    QCustomPlot *plot ;	     //传入实例化的QcustomPlot
    QCPGraph *graph;	   	 //这里是存传入的绘图图层
    QCPItemTracer *tracer;   // 跟踪的点
    QCPItemText *label;   	 // 显示的数值
    QCPItemLine *arrow;  	 // 箭头

    TracerType type;
    bool visible;

signals:

public slots:

};

#endif // MYTRACER_H
#include "mytracer.h"

myTracer::myTracer(QCustomPlot *_plot, QCPGraph *_graph, TracerType _type) : plot(_plot),
    graph(_graph),
    type(_type),
    visible(false)

{ 
   
    if (plot)
    { 
   
        tracer = new QCPItemTracer(plot);
        tracer->setStyle(QCPItemTracer::tsPlus);//可以选择设置追踪光标的样式,这个是小十字,还有大十字,圆点等样式
// tracer->setPen(QPen(Qt::red));
        tracer->setPen(graph->pen());//设置tracer的颜色
        tracer->setBrush(graph->pen().color());
        tracer->setSize(10);

        label = new QCPItemText(plot);
        label->setLayer("overlay");
        label->setClipToAxisRect(false);
        label->setPadding(QMargins(5, 5, 5, 5));

        label->position->setParentAnchor(tracer->position);
        label->setFont(QFont("宋体", 10));

        arrow = new QCPItemLine(plot);
        arrow->setLayer("overlay");
        arrow->setPen(graph->pen());//设置箭头的颜色
        arrow->setClipToAxisRect(false);
        arrow->setHead(QCPLineEnding::esSpikeArrow);

        switch (type) { 
   
        case XAxisTracer:
        { 
   
            tracer->position->setTypeX(QCPItemPosition::ptPlotCoords);
            tracer->position->setTypeY(QCPItemPosition::ptAxisRectRatio);
            label->setBrush(QBrush(QColor(244, 244, 244, 100)));
            label->setPen(QPen(Qt::black));

            label->setPositionAlignment(Qt::AlignTop|Qt::AlignHCenter);

            arrow->end->setParentAnchor(tracer->position);
            arrow->start->setParentAnchor(arrow->end);
            arrow->start->setCoords(20, 0);//偏移量
            break;
        }
        case YAxisTracer:
        { 
   
            tracer->position->setTypeX(QCPItemPosition::ptAxisRectRatio);
            tracer->position->setTypeY(QCPItemPosition::ptPlotCoords);

            label->setBrush(QBrush(QColor(244, 244, 244, 100)));
            label->setPen(QPen(Qt::black));
            label->setPositionAlignment(Qt::AlignRight|Qt::AlignHCenter);

            arrow->end->setParentAnchor(tracer->position);
            arrow->start->setParentAnchor(label->position);
            arrow->start->setCoords(-20, 0);//偏移量
            break;
        }
        case DataTracer:
        { 
   
            tracer->position->setTypeX(QCPItemPosition::ptPlotCoords);
            tracer->position->setTypeY(QCPItemPosition::ptPlotCoords);

            label->setBrush(QBrush(QColor(244, 244, 244, 150)));
            label->setPen(graph->pen());
            label->setPositionAlignment(Qt::AlignLeft|Qt::AlignVCenter);

            arrow->end->setParentAnchor(tracer->position);
            arrow->start->setParentAnchor(arrow->end);
            arrow->start->setCoords(25, 0);
            break;
        }

        default:
            break;
        }

        setVisible(false);
    }
}

myTracer::~myTracer()
{ 
   
    if (tracer)
        plot->removeItem(tracer);
    if (label)
        plot->removeItem(label);
}

void myTracer::setPen(const QPen &pen)
{ 
   
    tracer->setPen(pen);
    arrow->setPen(pen);
}

void myTracer::setBrush(const QBrush &brush)
{ 
   
    tracer->setBrush(brush);
}

void myTracer::setLabelPen(const QPen &pen)
{ 
   
    label->setPen(pen);
}

void myTracer::setText(const QString &text)
{ 
   
    label->setText(text);
}

void myTracer::setVisible(bool visible)
{ 
   
    tracer->setVisible(visible);
    label->setVisible(visible);
    arrow->setVisible(visible);
}

void myTracer::updatePosition(double xValue, double yValue)
{ 
   
    if (!visible)
    { 
   
        setVisible(true);
        visible = true;
    }
    if (yValue > plot->yAxis->range().upper)
        yValue = plot->yAxis->range().upper;
    switch (type) { 
   
    case XAxisTracer:
    { 
   
        tracer->position->setCoords(xValue, 1);
        label->position->setCoords(0, 15);
        arrow->start->setCoords(0, 15);
        arrow->end->setCoords(0, 0);

        break;
    }
    case YAxisTracer:
    { 
   
        tracer->position->setCoords(1, yValue);
        label->position->setCoords(-20, 0);
        break;
    }
    case DataTracer:
    { 
   
        tracer->position->setCoords(xValue, yValue);
        label->position->setCoords(25, 0);
        break;
    }
    default:
        break;
    }
}

附上我的实现主函数

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFile>
#include <QTextStream>
#include <string>


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{ 
   
    ui->setupUi(this);


    m_Plot = QSharedPointer<QCustomPlot> (new QCustomPlot());
    ui->verticalLayout->addWidget(m_Plot.data());
    //设置基本坐标轴(左侧Y轴和下方X轴)可拖动、可缩放、曲线可选、legend可选、设置伸缩比例,使所有图例可见
    m_Plot->setInteractions(QCP::iRangeDrag|QCP::iRangeZoom| QCP::iSelectAxes
                                |QCP::iSelectLegend | QCP::iSelectPlottables);
    m_Plot->legend->setVisible(true);
    m_Plot->legend->setFont(QFont("Helvetica",9));
    m_Plot->legend->setBrush(QColor(255,255,255,100));


    // generate some data:
    QVector<double> x(1000001), y(1000001), y1(1000001), y2(1000001);
    for (int i=0; i<1000001; ++i)
    { 
   
      x[i] = i;
      y[i] = x[i]/50000 * x[i]/50000;
      y1[i] = y[i] * 1.2;
      y2[i] = y[i] * 1.4;
    }
    QVector<QVector<double> > vec;
    vec.push_back(x);
    vec.push_back(y);
    m_value.push_back(vec);
    QVector<QVector<double> >().swap(vec);
    vec.push_back(x);
    vec.push_back(y1);
    m_value.push_back(vec);
    QVector<QVector<double> >().swap(vec);
    vec.push_back(x);
    vec.push_back(y2);
    m_value.push_back(vec);
    QVector<QVector<double> >().swap(vec);

    StaticDataPlot(m_value);
    m_Plot->xAxis->rescale(true);
    m_Plot->axisRect()->axis(QCPAxis::atBottom, 0)->setPadding(10); // add some padding to have space for tags

    m_TraserX = QSharedPointer<myTracer> (new myTracer(m_Plot.data(), m_Plot->graph(0), XAxisTracer));
    connect(m_Plot.data(), SIGNAL(mouseMove(QMouseEvent*)), this,SLOT(showTracer(QMouseEvent*)));
    m_Plot->replot();

}

MainWindow::~MainWindow()
{ 
   
    delete ui;
}

void MainWindow::showTracer(QMouseEvent *event)
{ 
   
    double x = m_Plot->xAxis->pixelToCoord(event->pos().x());
    m_TraserX->updatePosition(x, 0);
    m_TraserX->setText(QString::number(x, 'f', 2));
    for(int i=0;i<m_Graph.size();i++)
    { 
   
        double y = 0;
        QSharedPointer<QCPGraphDataContainer> tmpContainer;
        tmpContainer = m_Graph[i]->data();
        //使用二分法快速查找所在点数据!!!敲黑板,下边这段是重点
        int low = 0, high = tmpContainer->size();
        while(high > low)
        { 
   
            int middle = (low + high) / 2;
            if(x < tmpContainer->constBegin()->mainKey() ||
                    x > (tmpContainer->constEnd()-1)->mainKey())
                break;

            if(x == (tmpContainer->constBegin() + middle)->mainKey())
            { 
   
                y = (tmpContainer->constBegin() + middle)->mainValue();
                break;
            }
            if(x > (tmpContainer->constBegin() + middle)->mainKey())
            { 
   
                low = middle;
            }
            else if(x < (tmpContainer->constBegin() + middle)->mainKey())
            { 
   
                high = middle;
            }
            if(high - low <= 1)
            { 
      //差值计算所在位置数据
                y = (tmpContainer->constBegin()+low)->mainValue() + ( (x - (tmpContainer->constBegin() + low)->mainKey()) *
                    ((tmpContainer->constBegin()+high)->mainValue() - (tmpContainer->constBegin()+low)->mainValue()) ) /
                    ((tmpContainer->constBegin()+high)->mainKey() - (tmpContainer->constBegin()+low)->mainKey());
                break;
            }

        }

        m_Tracer[i]->updatePosition(x, y);
        m_Tracer[i]->setText(QString::number(y, 'f', 2));
    }
    m_Plot->replot();
}

介于很多小伙伴找我咨询代码问题,找到之前面目全非的代码重新修改编译了一下,可能有一点小不同但是效果相同,小手点下关注再去下载哦~
CustomPlotTest.zip

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/181226.html原文链接:https://javaforall.net

赞 (0)
全栈程序员-站长的头像全栈程序员-站长

相关推荐

  • servlet中init-param与context-param的区别「建议收藏」

    servlet中init-param与context-param的区别「建议收藏」init-paramweb.xml中的写法&lt;servlet&gt;&lt;servlet-name&gt;demo01&lt;/servlet-name&gt;&lt;servlet-class&gt;com.lanou3g.Demo01&lt;/servlet-class&gt;&lt;init-param&gt;&lt;pa…

    2022年7月16日
  • oracle11g安装图解「建议收藏」

    oracle11g安装图解「建议收藏」Oracle11g安装:**一、软件需求安装CentOS6.5的服务器一台Oracle11g安装介质:linux.x64_11gR2_database_1of2.ziplinux.x64_11gR2_database_2of2.zip命令行客户端工具xshell、crt或者putty图形界面客户端工具Xming二、系统配置检查1.内存检查SSHSecureShell的命令行窗口,执行[root@localhost~]#grepMemTotal/proc/meminfoM

    2022年9月21日
  • NoSuchMethodException解决「建议收藏」

    NoSuchMethodException解决「建议收藏」java.lang.NoSuchMethodException:com.test.action.test.findfinish()解决办法:1.检查action层是否存在该方法2.检查该方法是否为public3.检查此方法是否传了参数,[java]viewplaincopypublicStringtest(longid){return

    2022年6月16日
  • Generic Host process for Win32 service 解决办法「建议收藏」

    Generic Host process for Win32 service 解决办法「建议收藏」在开始–>运行(或者使用快捷键:windows+R)中输入regsvr32Urlmon.dll(enter)  regsvr32Shdocvw.dll(enter)  regsvr32Msjava.dll(enter)  regsvr32Actxprxy.dll(enter)  regsvr32Oleaut32.dll(enter)  regsvr32Mshtml.dll(enter)  regsvr32Browseui.dll(e

    2022年10月12日
  • python django环境搭建_python的django框架

    python django环境搭建_python的django框架Django是一个由Python编写的一个开放源代码的Web应用框架。使用Django,只要很少的代码,Python的开发人员就可以轻松地完成一个正式网站所需要的大部分内容,并进一步开发出全功能的Web服务。Python+Django是快速开发、设计、部署网站的最佳组合。Django版本与Python环境的对应表如下,建议对照表来选择Django和Python版本,以免造成不兼容等问题。 Django版本 Python版本 …

    2022年9月7日
  • 计算机网络原理(谢希仁第八版)第五章课后习题答案

    计算机网络原理(谢希仁第八版)第五章课后习题答案第五章1.试说明运输层在协议栈中的地位和作用,运输层的通信和网络层的通信有什么重要区别?为什么运输层是必不可少的?答:运输层处于面向通信部分的最高层,同时也是用户功能中的最低层,向它上面的应用层提供服务运输层为应用进程之间提供端到端的逻辑通信,但网络层是为主机之间提供逻辑通信(面向主机,承担路由功能,即主机寻址及有效的分组交换)。各种应用进程之间通信需要“可靠或尽力而为”的两类服务质量,必须由运输层以复用和分用的形式加载到网络层。2.网络层提供数据报或虚电路服务对上面的运输层有何影响

    2022年9月28日

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号