跟随鼠标动态显示线上点的值(基于Qt的开源绘图控件QCustomPlot进行二次开发)

本文为转载
原文链接:
采用Qt快速绘制多条曲线(折线),跟随鼠标动态显示线上点的值(基于Qt的开源绘图控件QCustomPlot进行二次开发)

内容如下

QCustomPlot是一个开源的基于Qt的第三方绘图库,能够绘制漂亮的2D图形。

QCustomPlot的官方网址:Qt Plotting Widget QCustomPlot - Introduction

从官网下载QCustomPlot的源文件,包括qcustomplot.h和qcustomplot.cpp。

本程序的源码下载地址: https://github.com/xiongxw/XCustomPlot.git

1 自定义鼠标显示跟随类XxwTracer和XxwTraceLine:

XxwTracer用于在图表中显示鼠标所在位置的x,y值

XxwTraceLine用于在图中显示水平或垂直的虚线

头文件XxwTracer.h

#ifndef MYTRACER_H
#define MYTRACER_H#include <QObject>
#include "qcustomplot.h"///
/// \brief The XxwTracer class:在图表中显示鼠标所在位置的x,y值的追踪显示器
///
class XxwTracer : public QObject
{
Q_OBJECTpublic:
enum TracerType
{XAxisTracer,//依附在x轴上显示x值YAxisTracer,//依附在y轴上显示y值DataTracer//在图中显示x,y值
};explicit XxwTracer(QCustomPlot *_plot, TracerType _type, QObject *parent = Q_NULLPTR);~XxwTracer();
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);void setVisible(bool m_visible);protected:bool m_visible;//是否可见TracerType m_type;//类型QCustomPlot *m_plot;//图表QCPItemTracer *m_tracer;//跟踪的点QCPItemText *m_label;//显示的数值QCPItemLine *m_arrow;//箭头
};///
/// \brief The XxwCrossLine class:用于显示鼠标移动过程中的鼠标位置的直线
///
class XxwTraceLine : public QObject
{
public:enum LineType{VerticalLine,//垂直线HorizonLine, //水平线Both//同时显示水平和垂直线};explicit XxwTraceLine(QCustomPlot *_plot, LineType _type = VerticalLine, QObject *parent = Q_NULLPTR);~XxwTraceLine();void initLine();void updatePosition(double xValue, double yValue);void setVisible(bool vis){if(m_lineV)m_lineV->setVisible(vis);if(m_lineH)m_lineH->setVisible(vis);}protected:bool m_visible;//是否可见LineType m_type;//类型QCustomPlot *m_plot;//图表QCPItemStraightLine *m_lineV; //垂直线QCPItemStraightLine *m_lineH; //水平线
};#endif // MYTRACER_H

源文件MyTracer.cpp

#include "MyTracer.h"XxwTracer::XxwTracer(QCustomPlot *_plot, TracerType _type, QObject *parent): QObject(parent),m_plot(_plot),m_type(_type)
{m_visible = true;m_tracer = Q_NULLPTR;// 跟踪的点m_label = Q_NULLPTR;// 显示的数值m_arrow = Q_NULLPTR;// 箭头if (m_plot){QColor clrDefault(Qt::red);QBrush brushDefault(Qt::NoBrush);QPen penDefault(clrDefault);//        penDefault.setBrush(brushDefault);penDefault.setWidthF(0.5);m_tracer = new QCPItemTracer(m_plot);m_tracer->setStyle(QCPItemTracer::tsCircle);m_tracer->setPen(penDefault);m_tracer->setBrush(brushDefault);m_label = new QCPItemText(m_plot);m_label->setLayer("overlay");m_label->setClipToAxisRect(false);m_label->setPadding(QMargins(5, 5, 5, 5));m_label->setBrush(brushDefault);m_label->setPen(penDefault);m_label->position->setParentAnchor(m_tracer->position);
//        m_label->setFont(QFont("宋体", 8));m_label->setFont(QFont("Arial", 8));m_label->setColor(clrDefault);m_label->setText("");m_arrow = new QCPItemLine(m_plot);QPen  arrowPen(clrDefault, 1);m_arrow->setPen(penDefault);m_arrow->setLayer("overlay");m_arrow->setClipToAxisRect(false);m_arrow->setHead(QCPLineEnding::esSpikeArrow);//设置头部为箭头形状switch (m_type){case XAxisTracer:{m_tracer->position->setTypeX(QCPItemPosition::ptPlotCoords);m_tracer->position->setTypeY(QCPItemPosition::ptAxisRectRatio);m_tracer->setSize(7);m_label->setPositionAlignment(Qt::AlignTop | Qt::AlignHCenter);m_arrow->end->setParentAnchor(m_tracer->position);m_arrow->start->setParentAnchor(m_arrow->end);m_arrow->start->setCoords(0, 20);//偏移量break;}case YAxisTracer:{m_tracer->position->setTypeX(QCPItemPosition::ptAxisRectRatio);m_tracer->position->setTypeY(QCPItemPosition::ptPlotCoords);m_tracer->setSize(7);m_label->setPositionAlignment(Qt::AlignRight | Qt::AlignHCenter);m_arrow->end->setParentAnchor(m_tracer->position);m_arrow->start->setParentAnchor(m_label->position);m_arrow->start->setCoords(-20, 0);//偏移量break;}case DataTracer:{m_tracer->position->setTypeX(QCPItemPosition::ptPlotCoords);m_tracer->position->setTypeY(QCPItemPosition::ptPlotCoords);m_tracer->setSize(5);m_label->setPositionAlignment(Qt::AlignLeft | Qt::AlignVCenter);m_arrow->end->setParentAnchor(m_tracer->position);m_arrow->start->setParentAnchor(m_arrow->end);m_arrow->start->setCoords(20, 0);break;}default:break;}setVisible(false);}
}XxwTracer::~XxwTracer()
{if(m_plot){if (m_tracer)m_plot->removeItem(m_tracer);if (m_label)m_plot->removeItem(m_label);if (m_arrow)m_plot->removeItem(m_arrow);}
}void XxwTracer::setPen(const QPen &pen)
{if(m_tracer)m_tracer->setPen(pen);if(m_arrow)m_arrow->setPen(pen);
}void XxwTracer::setBrush(const QBrush &brush)
{if(m_tracer)m_tracer->setBrush(brush);
}void XxwTracer::setLabelPen(const QPen &pen)
{if(m_label){m_label->setPen(pen);m_label->setBrush(Qt::NoBrush);m_label->setColor(pen.color());}
}void XxwTracer::setText(const QString &text)
{if(m_label)m_label->setText(text);
}void XxwTracer::setVisible(bool vis)
{m_visible = vis;if(m_tracer)m_tracer->setVisible(m_visible);if(m_label)m_label->setVisible(m_visible);if(m_arrow)m_arrow->setVisible(m_visible);
}void XxwTracer::updatePosition(double xValue, double yValue)
{if (!m_visible){setVisible(true);m_visible = true;}if (yValue > m_plot->yAxis->range().upper)yValue = m_plot->yAxis->range().upper;switch (m_type){case XAxisTracer:{m_tracer->position->setCoords(xValue, 1);m_label->position->setCoords(0, 15);m_arrow->start->setCoords(0, 15);m_arrow->end->setCoords(0, 0);setText(QString::number(xValue));break;}case YAxisTracer:{m_tracer->position->setCoords(0, yValue);m_label->position->setCoords(-20, 0);
//        m_arrow->start->setCoords(20, 0);
//        m_arrow->end->setCoords(0, 0);setText(QString::number(yValue));break;}case DataTracer:{m_tracer->position->setCoords(xValue, yValue);m_label->position->setCoords(20, 0);setText(QString("x:%1,y:%2").arg(xValue).arg(yValue));break;}default:break;}
}XxwTraceLine::XxwTraceLine(QCustomPlot *_plot, LineType _type, QObject *parent): QObject(parent),m_type(_type),m_plot(_plot)
{m_lineV = Q_NULLPTR;m_lineH = Q_NULLPTR;initLine();
}XxwTraceLine::~XxwTraceLine()
{if(m_plot){if (m_lineV)m_plot->removeItem(m_lineV);if (m_lineH)m_plot->removeItem(m_lineH);}
}void XxwTraceLine::initLine()
{if(m_plot){QPen linesPen(Qt::red, 1, Qt::DashLine);if(VerticalLine == m_type || Both == m_type){m_lineV = new QCPItemStraightLine(m_plot);//垂直线m_lineV->setLayer("overlay");m_lineV->setPen(linesPen);m_lineV->setClipToAxisRect(true);m_lineV->point1->setCoords(0, 0);m_lineV->point2->setCoords(0, 0);}if(HorizonLine == m_type || Both == m_type){m_lineH = new QCPItemStraightLine(m_plot);//水平线m_lineH->setLayer("overlay");m_lineH->setPen(linesPen);m_lineH->setClipToAxisRect(true);m_lineH->point1->setCoords(0, 0);m_lineH->point2->setCoords(0, 0);}}
}void XxwTraceLine::updatePosition(double xValue, double yValue)
{if(VerticalLine == m_type || Both == m_type){if(m_lineV){m_lineV->point1->setCoords(xValue, m_plot->yAxis->range().lower);m_lineV->point2->setCoords(xValue, m_plot->yAxis->range().upper);}}if(HorizonLine == m_type || Both == m_type){if(m_lineH){m_lineH->point1->setCoords(m_plot->xAxis->range().lower, yValue);m_lineH->point2->setCoords(m_plot->xAxis->range().upper, yValue);}}
}

2 自定义的图表类XCustomPlot

XCustomPlot是基于QCustomPlot二次开发的图表类,在鼠标移动过程中动态显示曲线上点的值。

头文件XCustomPlot.h

#ifndef XCUSTOMPLOT_H
#define XCUSTOMPLOT_H#include "XxwTracer.h"
#include "qcustomplot.h"
#include <QObject>
#include <QList>class XxwCustomPlot:public QCustomPlot
{Q_OBJECTpublic:XxwCustomPlot(QWidget *parent = 0);protected:virtual void mouseMoveEvent(QMouseEvent *event);public:////// \brief 设置是否显示鼠标追踪器/// \param show:是否显示///void showTracer(bool show){m_isShowTracer = show;if(m_xTracer)m_xTracer->setVisible(m_isShowTracer);foreach (XxwTracer *tracer, m_dataTracers){if(tracer)tracer->setVisible(m_isShowTracer);}if(m_lineTracer)m_lineTracer->setVisible(m_isShowTracer);}////// \brief 是否显示鼠标追踪器/// \return///bool isShowTracer(){return m_isShowTracer;};private:bool m_isShowTracer;//是否显示追踪器(鼠标在图中移动,显示对应的值)XxwTracer *m_xTracer;//x轴XxwTracer *m_yTracer;//y轴QList<XxwTracer *> m_dataTracers;//XxwTraceLine  *m_lineTracer;//直线
};#endif // XCUSTOMPLOT_H

源文件XCustomPlot.h

#include "XxwCustomPlot.h"XxwCustomPlot::XxwCustomPlot(QWidget *parent):QCustomPlot(parent),m_isShowTracer(false),m_xTracer(Q_NULLPTR),m_yTracer(Q_NULLPTR),m_dataTracers(QList<XxwTracer *>()),m_lineTracer(Q_NULLPTR)
{
}void XxwCustomPlot::mouseMoveEvent(QMouseEvent *event)
{QCustomPlot::mouseMoveEvent(event);if(m_isShowTracer){//当前鼠标位置(像素坐标)int x_pos = event->pos().x();int y_pos = event->pos().y();//像素坐标转成实际的x,y轴的坐标float x_val = this->xAxis->pixelToCoord(x_pos);float y_val = this->yAxis->pixelToCoord(y_pos);if(Q_NULLPTR == m_xTracer)m_xTracer = new XxwTracer(this, XxwTracer::XAxisTracer);//x轴m_xTracer->updatePosition(x_val, y_val);if(Q_NULLPTR == m_yTracer)m_yTracer = new XxwTracer(this, XxwTracer::YAxisTracer);//y轴m_yTracer->updatePosition(x_val, y_val);int nTracerCount = m_dataTracers.count();int nGraphCount = graphCount();if(nTracerCount < nGraphCount){for(int i = nTracerCount; i < nGraphCount; ++i){XxwTracer *tracer = new XxwTracer(this, XxwTracer::DataTracer);m_dataTracers.append(tracer);}}else if(nTracerCount > nGraphCount){for(int i = nGraphCount; i < nTracerCount; ++i){XxwTracer *tracer = m_dataTracers[i];if(tracer){tracer->setVisible(false);}}}for (int i = 0; i < nGraphCount; ++i){XxwTracer *tracer = m_dataTracers[i];if(!tracer)tracer = new XxwTracer(this, XxwTracer::DataTracer);tracer->setVisible(true);tracer->setPen(this->graph(i)->pen());tracer->setBrush(Qt::NoBrush);tracer->setLabelPen(this->graph(i)->pen());auto iter = this->graph(i)->data()->findBegin(x_val);double value = iter->mainValue();
//            double value = this->graph(i)->data()->findBegin(x_val)->value;tracer->updatePosition(x_val, value);}if(Q_NULLPTR == m_lineTracer)m_lineTracer = new XxwTraceLine(this,XxwTraceLine::Both);//直线m_lineTracer->updatePosition(x_val, y_val);this->replot();//曲线重绘}
}

3 使用自定义图表类XCustomPlot

在需要绘图的地方使用,代码如下:

  m_customPlot = new XxwCustomPlot();m_customPlot->showTracer(true);// add title layout element:m_customPlot->plotLayout()->insertRow(0);m_customPlot->plotLayout()->addElement(0, 0, new QCPTextElement(m_customPlot, "标题", QFont("黑体", 12, QFont::Bold)));m_customPlot->legend->setVisible(true);QFont legendFont = font();  // start out with MainWindow's font..legendFont.setPointSize(9); // and make a bit smaller for legendm_customPlot->legend->setFont(legendFont);m_customPlot->legend->setBrush(QBrush(QColor(255,255,255,230)));// by default, the legend is in the inset layout of the main axis rect. So this is how we access it to change legend placement:m_customPlot->axisRect()->insetLayout()->setInsetAlignment(0, Qt::AlignTop|Qt::AlignCenter);// make left and bottom axes always transfer their ranges to right and top axes:connect(m_customPlot->xAxis, SIGNAL(rangeChanged(QCPRange)), m_customPlot->xAxis2, SLOT(setRange(QCPRange)));connect(m_customPlot->yAxis, SIGNAL(rangeChanged(QCPRange)), m_customPlot->yAxis2, SLOT(setRange(QCPRange)));// Allow user to drag axis ranges with mouse, zoom with mouse wheel and select graphs by clicking:m_customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);// generate some data:int nCount = 100;QVector<double> x(nCount), y0(nCount), y1(nCount); // initialize with entries 0..100for (int i = 0; i < nCount; ++i){x[i] = i; // x goes from -1 to 1y0[i] = qSin(i * 10.0f / nCount); //siny1[i] = qCos(i * 10.0f / nCount); //cos}// create graph and assign data to it:QPen pen;int i = 1;QCPGraph *pGraph = m_customPlot->addGraph();//        m_customPlot->graph(0)->setData(x, y0);pGraph->setName("sin曲线");pGraph->setData(x,y0);pGraph->setPen(QPen(Qt::blue));pGraph = m_customPlot->addGraph();//        m_customPlot->graph(0)->setData(x, y0);pGraph->setName("cos曲线");pGraph->setData(x,y1);pGraph->setPen(QPen(Qt::darkYellow));// give the axes some labels:m_customPlot->xAxis->setLabel("x");m_customPlot->yAxis->setLabel("y");// set axes ranges, so we see all data:
//    m_customPlot->xAxis->setRange(-1, 1);
//    m_customPlot->yAxis->setRange(0, 1);m_customPlot->rescaleAxes(true);m_customPlot->replot();

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/225352.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

打工人副业变现秘籍,某多/某手变现底层引擎-Stable Diffusion 黑白老照片上色修复

在这个时代,我们习惯于拥有高清、色彩丰富的照片,然而,那些古老的黑白色老照片由于年代的久远,往往会出现模糊、破损等现象。 那么今天要给大家介绍的是,用 Stable Diffusion 来修复老照片。 前段时间 ControlNet 的除了上线了“IP-Adapter”模型以外还增加另一个…

【深度学习】TensorFlow深度模型构建:训练一元线性回归模型

文章目录 1. 生成拟合数据集2. 构建线性回归模型数据流图3. 在Session中运行已构建的数据流图4. 输出拟合的线性回归模型5. TensorBoard神经网络数据流图可视化6. 完整代码 本文讲解&#xff1a; 以一元线性回归模型为例&#xff0c; 介绍如何使用TensorFlow 搭建模型 并通过会…

【Android12】Android Framework系列--AMS启动Activity分析

AMS启动Activity分析 通过ActivityManagerService(AMS)提供的方法&#xff0c;可以启动指定的Activity。比如Launcher中点击应用图标后&#xff0c;调用AMS的startActivity函数启动应用。 AMS提供的服务通过IActivityManager.aidl文件定义。 // frameworks/base/core/java/an…

KafKa基本原理

分布式&#xff0c;分区&#xff0c;多副本&#xff0c;zk协调的分布式消息系统 使用 日志收集 消息系统 用户活动跟踪 运营指标 概念 Broker topic producer consumer consumergroup partition 通信基于tcp协议 很多集群信息记录在zk里保证自己的无状态&#xff0c;方便…

使用Python将HTML快速转换成PDF

大家好&#xff0c;在Web开发和报告任务中&#xff0c;将HTML内容转换为PDF是一种常见需求。Python作为一个庞大的生态系统&#xff0c;提供了各种库来完成这个任务。本文将指导完成使用Python将HTML转换为PDF的过程&#xff0c;包括一个示例实现和一个单元测试。我们将使用pdf…

Python将已标注的两张图片进行上下拼接并修改、合并其对应的Labelme标注文件(v2.0)

Python将已标注的两张图片进行上下拼接并修改、合并其对应的Labelme标注文件&#xff08;v2.0&#xff09; 前言前提条件相关介绍实验环境上下拼接图片并修改、合并其对应的Labelme标注文件代码实现输出结果 前言 此版代码&#xff0c;相较于Python将已标注的两张图片进行上下拼…

shopify 跨境电商网站开发

开发团队&#xff08;5个人&#xff09;&#xff1a; Bobby&#xff1a;毕业于山西大学&#xff0c;软件工程专业&#xff0c;多年项目管理产品经理经验。 Alice&#xff1a;毕业于山西大学吕梁学院&#xff0c;信息于计算科学&#xff0c;多年前端开发经验。 Tiffany&#xff…

区块链的可扩展性研究【06】Plasma

1.Plasma&#xff1a;Plasma 是一种基于以太坊区块链的 Layer2 扩容方案&#xff0c;它通过建立一个分层结构的区块链网络&#xff0c;将大量的交易放到子链上进行处理&#xff0c;从而提高了以太坊的吞吐量。Plasma 还可以通过智能合约实现跨链交易&#xff0c;使得不同的区块…

每日一道算法题 8(2023-12-16)

题目描述 给定一个仅包含0和1的n*n二维矩阵 请计算二维矩阵的最大值 计算规则如下 每行元素按下标顺序组成一个二进制数(下标越大约排在低位)&#xff0c; 二进制数的值就是该行的值&#xff0c;矩阵各行之和为矩阵的值 允许通过向左或向右整体循环移动每个元素来改变元素在行…

【面试】不使用中间变量,交换两个变量a和b的值

点评&#xff1a;典型的送人头的题目&#xff0c;通常交换两个变量需要借助一个中间变量&#xff0c;如果不允许使用中间变量&#xff0c;在其他编程语言中可以使用异或运算的方式来实现交换两个变量的值&#xff0c;但是Python中有更为简单明了的做法。 方法一&#xff1a; …

芯知识 | WT2003Hx系列高品质语音芯片MP3音频解码IC的特征与应用优势

在嵌入式语音领域&#xff0c;唯创知音WT2003Hx系列高品质语音芯片以其卓越的音频解码性能脱颖而出。本文将深入研究该系列芯片的特色与应用优势&#xff0c;重点关注其支持wav、Mp3格式音频解码、高品质播放等方面。 特色一&#xff1a;支持wav、Mp3格式音频解码 1.多格式兼…

【️Zookeeper是CP还是AP的?】

&#x1f60a;引言 &#x1f396;️本篇博文约3000字&#xff0c;阅读大约10分钟&#xff0c;亲爱的读者&#xff0c;如果本博文对您有帮助&#xff0c;欢迎点赞关注&#xff01;&#x1f60a;&#x1f60a;&#x1f60a; &#x1f5a5;️Zookeeper是CP还是AP的&#xff1f; ✅…

爬虫中HTTP请求库和requestsxiang详解

Requests: 让 HTTP 服务人类 虽然Python的标准库中 urllib 模块已经包含了平常我们使用的大多数功能&#xff0c;但是它的 API 使用起来让人感觉不太好&#xff0c;而 Requests 自称 “HTTP for Humans”&#xff0c;说明使用更简洁方便。 Requests 唯一的一个非转基因的 Pyth…

2024年20多个最有创意的AI人工智能点子

我的新书《Android App开发入门与实战》已于2020年8月由人民邮电出版社出版&#xff0c;欢迎购买。点击进入详情 探索 2024 年将打造的 20 个基于人工智能产品的盈利创意 &#x1f525;&#x1f525;&#x1f525; 直到最近&#xff0c;企业对人工智能还不感兴趣&#xff0c;但…

浅析AI视频分析与视频管理系统EasyCVR平台及场景应用

人工智能的战略重要性导致对视频智能分析的需求不断增加。鉴于人工智能视觉技术的巨大潜力&#xff0c;人们的注意力正在从传统的视频监控转移到计算机视觉的监控过程自动化。 1、什么是视频分析&#xff1f; 视频分析或视频识别技术&#xff0c;是指从视频片段中提取有用信息…

存放redis异常Could not write JSON: Java 8 date/time type `java.time.LocalDateTime处理

1.首先需要maven引入 <dependency><artifactId>jackson-datatype-jsr310</artifactId><groupId>com.fasterxml.jackson.datatype</groupId><version>2.15.3</version></dependency>2.示例代码如下 private RedisTemplate<S…

Java设计模式-建造者模式

目录 一、需求 二、传统方法解决需求 三、基本介绍 四、注意事项和细节 一、需求 盖房项目需求 需要建房子&#xff1a;这一过程为打桩、砌墙、封顶 房子有各种各样的&#xff0c;比如普通房&#xff0c;高楼&#xff0c;别墅&#xff0c;各种房子的过程虽然一样&#xff…

RabbitMQ插件详解:rabbitmq_message_timestamp【Rabbitmq 五】

欢迎来到我的博客&#xff0c;代码的世界里&#xff0c;每一行都是一个故事 RabbitMQ时空之旅&#xff1a;rabbitmq_message_timestamp的奇妙世界 前言什么是rabbitmq_message_timestamprabbitmq_message_timestamp 的定义与作用&#xff1a;如何在 RabbitMQ 中启用消息时间戳&…

【每次启动wsl时自动更新ip】

每次启动wsl时自动更新ip 在windows中使用wsl时&#xff0c;每次启动wsl后发现其ip都会改变&#xff0c;这样的话如果想通过vscode的Remote-SSH插件打开代码编辑器&#xff0c;就需要手动更新ssh配置文件&#xff0c;极为不便&#xff0c;所以考虑使用一种优雅的方式&#xff0…

abc组合 C语言xdoj54

问题描述 已知abccban&#xff0c;其中a,b,c均为一位数&#xff0c;1000<n<2000,编程求出满足条件的a,b,c所有组合。 输入说明 一个整数n 输出说明 按照整数abc从小到大的顺序,输出a, b, c, 用空格分隔&#xff0c;每输出一组a&#xff0c;b&#xff0c;c后换…