欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Qt自定义Plot实现曲线绘制的详细过程

程序员文章站 2022-03-13 10:23:29
简介实现了qt绘制曲线功能,包含arm触摸屏多点触控缩放(只支持两点),实时曲线绘制,数据点根据绘制宽度优化,跟踪点数据获取,双坐标等功能演示代码头文件 plot.h/* * 作者:老人与海 * 博客...

简介

实现了qt绘制曲线功能,包含arm触摸屏多点触控缩放(只支持两点),实时曲线绘制,数据点根据绘制宽度优化,跟踪点数据获取,双坐标等功能

演示

Qt自定义Plot实现曲线绘制的详细过程

Qt自定义Plot实现曲线绘制的详细过程

代码

头文件 plot.h

/*
 * 作者:老人与海
 * 博客:https://blog.csdn.net/qq_41340733
 * 代码不保证稳定性,请勿用于商业用途
 */

#ifndef plot_h
#define plot_h

#include <qwidget>
#include <qtimer>
#include <qlist>
#include <qwheelevent>
#include <qmouseevent>
#include "plotdata.h"
typedef struct _rangeval
{
    double beg;
    double end;
    double offset;
    bool isoffset;
    _rangeval()
    {
        beg=0;
        end=0;
        offset=0;
        isoffset=false;
    }
}_rangeval;

//鼠标跟中点
class tracking
{
public:
    tracking()
    {
        m_isdraw=false;
        m_ismove=false;
        m_isinit=false;
        m_first=false;
        m_radius=25;
        m_pointcenter=qpoint(0,0);
    }
    ~tracking(){}
    bool getisrange(qpoint point)
    {
        if(point.x()>(m_pointcenter.x()-m_radius)&&
                point.x()<(m_pointcenter.x()+m_radius)&&
                point.y()>(m_pointcenter.y()-m_radius)&&
                point.y()<(m_pointcenter.y()+m_radius))
        {
            return true;
        }else{
            return false;
        }
    }
public:
    bool m_isdraw;
    bool m_ismove;//鼠标焦点
    bool m_isinit;
    bool m_first;
    int m_radius;
    qpoint m_pointcenter;//绘制圆心
};

/**
 * @brief the cooraxis class
 * 类名:cooraxis
 * 功能:坐标轴部件,用来绘制xy坐标轴,使用时必须用plot的ticker类进行初始化,否则无法正常绘制坐标
 */
class cooraxis : public qwidget
{
    q_object
public:
    explicit cooraxis(qwidget *parent = nullptr,ticker *ticker= nullptr);
    virtual ~cooraxis();

    ticker *ticker(){ return m_ticker; }
    void mousemove(qmouseevent *event);
signals:
    void sig_updateui();
public slots:
    void slots_sendcoorwheel(qwheelevent *event);
    void slots_sendcoormouse(qmouseevent *event,qpoint point,bool isfirst=false);
protected:
   void paintevent(qpaintevent *event);
   void drawtickerx(qpainter *painter);//绘制x轴
   void drawtickery_l(qpainter *painter);//绘制左边y轴
   void drawtickery_r(qpainter *painter);//绘制右边y轴
   void wheelevent(qwheelevent *event);//滚轮事件,缩放曲线图像
   void mousepressevent(qmouseevent *event);//按下事件,记录坐标和按下标志
   void mousereleaseevent(qmouseevent *event);//抬起事件,取消按下标志
   void mousemoveevent(qmouseevent *event);//鼠标移动事件,移动曲线

protected:
   ticker *m_ticker;
   int m_lastlength;
   int m_margin;

   bool ispress=false;
   qpoint m_firstpoint;
};


class plot : public qwidget
{
    q_object
public:
    explicit plot(qwidget *parent=nullptr);
    virtual ~plot();

    void valueinit();
    ticker *tickerx();
    ticker *tickerl();
    ticker *tickerr();
    void addgraph();
    void graphclear(){ m_xygraph.clear(); }
    int getgraphcount(){ return m_xygraph.count(); }
    _xylist *graph(int index);
    qlist<_xylist> &graphgroup(){ return m_xygraph; }
    void settrackvisibel(bool isvisbel){ m_tracking.m_isdraw=isvisbel; }
    bool gettrackvisibel(){ return m_tracking.m_isdraw; }
    void setisdrawpath(bool value){ m_isdrawpath=value; }
    bool getisdrawpath(){ return m_isdrawpath; }

    void coordtopixel(_coordinatevalue *value,_tickertype type);
    void coordtopixel(double &key,double &value,_tickertype type);
    void pixeltocoorkey(double &key,_tickertype type);
    void pixeltocoorvalue(double &value,_tickertype type);
    void pixeltocoord(qpointf &pointf,_tickertype type);
    void getoptimizedlinedata(qvector<qpointf> *linedata,int index);

    void calculatetrackvalue(qpoint point);
    void setbackgroundcolor(qcolor color){ m_backgroundcolor=color; }
    qcolor getbackgroundcolor(){ return m_backgroundcolor; }
signals:
    void sig_sendcoorwheel(qwheelevent *event);
    void sig_sendcoormouse(qmouseevent *event,qpoint point,bool isfirst=false);
    void sig_updateui();
    void sig_updatetrack();//刷新跟踪点数据
public slots:

protected:
   void paintevent(qpaintevent *event);
   void drawgrid(qpainter *painter);//绘制网格
   void drawpath(qpainter *painter);//绘制曲线
   void drawcursor(qpainter *painter);//绘制跟踪点
   void drawtickerx(qpainter *painter);//绘制x轴
   void drawtickery_l(qpainter *painter);//绘制左边y轴
   void drawtickery_r(qpainter *painter);//绘制右边y轴

   void wheelevent(qwheelevent *event);//滚轮事件,缩放曲线图像
   void mousepressevent(qmouseevent *event);//按下事件,记录坐标和按下标志
   void mousereleaseevent(qmouseevent *event);//抬起事件,取消按下标志
   void mousemoveevent(qmouseevent *event);//鼠标移动事件,移动曲线
   void showevent(qshowevent *event);//显示事件
   bool event(qevent *event);//事件,实现多点触控功能,目前只对两个触控点做了处理

public:
   qpixmap m_pixmapcursor;//跟踪点绘制图像缓冲
   tracking m_tracking;
protected:
   ticker *m_tickerx;
   ticker *m_tickerl;
   ticker *m_tickerr;

   bool ispress=false;
   bool m_istouch=false;

   qpoint m_clickedpoint;
   qreal m_scalefactorx=0.0;
   qreal m_scalefactory=0.0;
   qlist<_xylist> m_xygraph;

   qcolor m_backgroundcolor;
   bool m_isdrawpath;//是否绘制曲线,在多线程添加数据的时候调用,添加数据时禁止绘制曲线
private:
   friend class ticker;
};

class curvewid : public qwidget
{
    q_object
public:
    explicit curvewid(qwidget *parent = nullptr);

    void datainit();
    void reupdate();
    void reupdateall();
signals:

public slots:
    void slots_updateui();
    void slots_timeout();
protected:
    void paintevent(qpaintevent *event);
public:
    cooraxis *m_axisx;
    cooraxis *m_axisl;
    cooraxis *m_axisr;

    plot *m_plot;
    qtimer *m_timer;
};


#endif // plot_h

头文件plotdata.h

/*
 * 作者:老人与海 
 * 博客:https://blog.csdn.net/qq_41340733
 * 代码不保证稳定性,请勿用于商业用途
 */


#ifndef plotdata_h
#define plotdata_h

#include <qobject>
#include <qvector>
#include <qcolor>
class cooraxis;

//_coordinatevalue单个数据点结构体
typedef struct _coordinatevalue
{
    double key;
    double value;
    _coordinatevalue()
    {
        key=0;
        value=0;
    }
}_coordinatevalue;
//坐标轴绘制的文本类型,包括时间毫秒,时间秒,数值
typedef enum _text_type
{
    _timems,
    _times,
    countval
}_text_type;
//坐标轴类型,xaxis表示x轴,yaxis_l表示左边的y轴,yaxis_r表示右边的y轴
typedef enum _tickertype
{
    xaxis=0,
    yaxis_l=1,
    yaxis_r=2
}_tickertype;
//坐标缩放前的坐标值,_begval坐标起始值,_endval坐标结束值,_siteval坐标中点,
//多点触控的时候先记录坐标的原始值,然后根据手势距离对原始进行缩放
typedef struct _scale
{
    double _begval=0.0;
    double _endval=0.0;
    double _siteval=0.0;
}_scale;

/**
 * @brief the _xylist class
 * 功能:单条曲线的数据结构类型,包括坐标轴类型,曲线颜色,
 * 最多可绘制的曲线点数,等功能等;
 */
class _xylist
{
public:
    explicit _xylist();
    virtual ~_xylist(){}

    int count();//实际有效的数据点
    int countall();//所有的数据点,包括被移除的记录
    int getremovecount(){ return  m_removecount; }
    _coordinatevalue &getpoint(int index);
    void adddata(const double key,const double value);
    void removefirst();
    void cleanbuff();
    int size() const { return m_coodvalue.size()-m_removecount; }
    qvector<_coordinatevalue> *data();

    void setpointcountmax(int count);
    int getpointmax(){ return m_maxpointcount; }
    void setcolor(qcolor color){ m_color=color; }
    qcolor getcolor(){ return m_color; }
    void setaxistype(_tickertype type){ m_type=type; }
    _tickertype &getaixstype(){ return m_type; }

    int getbegindex(const double &tmpkey);
    int getendindex(const double &tmpkey);
    int getcoortoindex(const double &tmpkey);

    _coordinatevalue gettrackvalue(){ return trackvalue; }
    void settrackvalue(const _coordinatevalue value){ trackvalue=value; }
    void settrackvalue(const double key,const double value){
        trackvalue.key=key;
        trackvalue.value=value;
    }
    bool tracckisvalid(){ return isvalid; }
    void settrackisvalid(bool val){ isvalid=val; }

    void setvisible(bool val){ m_visible=val; }
    bool getvisible(){ return m_visible; }

    _coordinatevalue getmaxvalue(){ return m_maxvalue; }
    _coordinatevalue getminvalue(){ return m_minvalue; }

    qvector<_coordinatevalue>::const_iterator constbegite(){ return (m_coodvalue.begin()+m_removecount); }
    qvector<_coordinatevalue>::const_iterator constendite(){ return m_coodvalue.end(); }
protected:
    qvector<_coordinatevalue> m_coodvalue;
    int m_maxpointcount;//实际数据点,根据总数据点是否达到这和数目而对m_removecount进行操作
    int m_removecount;//被移除的次数,会先记录,到达一定数据时候会重新分分配m_coodvalue大小,提高了添加固定点数据时候的速度
    _tickertype m_type;
    qcolor m_color;
    _coordinatevalue trackvalue;//踪点的值
    bool isvalid;//判断跟踪点的值是否有效
    bool m_visible;//是否绘制,既可见度

    _coordinatevalue m_maxvalue;
    _coordinatevalue m_minvalue;
};
/**
 * @brief the ticker class
 * 坐标轴数据结构类,这里描述了坐标的主刻度,子刻度,刻度长度,
 * 坐标范围,坐标轴的类型(x还是y 参考_tickertype)等信息
 */
class ticker
{
public:
    explicit ticker()
    {
       mainlinecount=15;
       sublinecount=6;
       mainlength=10;
       sublength=10;
       type=_tickertype::xaxis;
       m_rangebeg=0;
       m_rangeend=500;
    }
    virtual ~ticker(){}

    void setmainlinecount(const int count){ mainlinecount=count; }
    void setsublinecount(const int count){ sublinecount=count; }
    void setmainlinelength(const int length){ mainlength=length; }
    void setsublinelength(const int length){ sublength=length; }
    void setaxistype(_tickertype type){ type=type; }
    void settexttype(_text_type type){ m_texttype=type; }
    void setrangebeg(const double &value);
    void setrangeend(const double &value);
    void setrange(const double &begvalue,const double &endvalue);
    void moverange(const double &value);//根据数值偏移,正数往前,负数往后
    void moverangepercent(const double &value);//根据百分比偏移,正数往前,负数往后
    void setzoom(const double value);//根据中心值进行缩放,大于1表示放大,小于1表示缩小

    int getmainlinecount(){ return mainlinecount; }
    int getsublinecount(){ return sublinecount; }
    int getmainlinelength(){ return mainlength; }
    int getsublinelength(){ return sublength; }
    _tickertype getaxistype(){ return type; }
    double getrangebeg(){ return m_rangebeg; }
    double getrangeend(){ return m_rangeend; }
    double getrangemidvalue(){ return (m_rangebeg+(m_rangeend-m_rangebeg)/2.0); }//获取轴的中心值
    _scale &getscale(){ return m_scale; }
    void initscale();
    void setscalecoor(const double scalefactor);//根据siteval左边点进行缩放
    _text_type gettexttype(){ return m_texttype; }
protected:
    int mainlinecount;
    int sublinecount;
    int mainlength;
    int sublength;
    double m_rangebeg;
    double m_rangeend;

    _tickertype type;
    _text_type m_texttype;
    _scale m_scale;
private:
   friend class cooraxis;
};
#endif // addpoint_h

头文件mainwindow.h

#ifndef mainwindow_h
#define mainwindow_h

#include <qmainwindow>
#include "qtimer.h"
#include "plot.h"
#include <qlabel>
qt_begin_namespace
namespace ui { class mainwindow; }
qt_end_namespace


class mainwindow : public qmainwindow
{
    q_object

public:
    mainwindow(qwidget *parent = nullptr);
    ~mainwindow();

public slots:
    void slots_timeout();
    void slots_refresh();
    void slots_updatetrack();
protected:
    qtimer *m_timer;
    qtimer *m_timerrefresh;

    curvewid *m_curve;

    qvector<qlabel *> m_lablist;
    bool isaddok=false;
private:
    ui::mainwindow *ui;
};
#endif // mainwindow_h

c文件

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <qdatetime>
#include <qdebug>
#include "qgridlayout.h"
#include "math.h"
#include "qpainter.h"
#include <qvboxlayout>
#include <qgridlayout>

#define _pointcount 50000
mainwindow::mainwindow(qwidget *parent)
    : qmainwindow(parent)
    , ui(new ui::mainwindow)
{
    ui->setupui(this);
    ui->statusbar->hide();


    ui->centralwidget->setstylesheet("qwidget{background-color: rgb(0, 0, 0);}");
    m_curve=new curvewid;
    connect(m_curve->m_plot,&plot::sig_updatetrack,this,&mainwindow::slots_updatetrack);

    m_timer=new qtimer(this);
    m_timerrefresh=new qtimer(this);
    m_timer->start(100);
    m_timerrefresh->start(100);
    connect(m_timer,&qtimer::timeout,this,&mainwindow::slots_timeout);
    connect(m_timerrefresh,&qtimer::timeout,this,&mainwindow::slots_refresh);

    m_curve->m_axisl->ticker()->setrange(-100,1200);
    m_curve->m_axisr->ticker()->setrange(-100,600);
    m_curve->m_axisx->ticker()->setrange(-100,_pointcount*0.01);
    qint64 time=qdatetime::currentmsecssinceepoch();
    m_curve->m_axisx->ticker()->settexttype(_text_type::_timems);
//    m_curve->m_axisx->ticker()->setrange(time-600000,time);

    qgridlayout *g_layout=new qgridlayout;
    g_layout->setverticalspacing(3);
    g_layout->setcontentsmargins(0,0,0,0);
    qsrand(qtime(0,0,0).secsto(qtime::currenttime()));
    for(int i=0;i<16;i++)
    {
        qlabel *labvalue=new qlabel;
        labvalue->settext(qstring("qlabel %1").arg(i+1));
        labvalue->setalignment(qt::aligncenter);
        labvalue->setstylesheet("qlabel{color:rgb(0, 122, 255);}");
        labvalue->setfixedheight(36);
        g_layout->addwidget(labvalue,i/8,i%8);

        qcolor color=qcolor(qrand() % 256, qrand() % 256, qrand() % 256);
        int r,g,b;
        color.getrgb(&r,&g,&b);
        labvalue->setstylesheet(qstring("qlabel{ color:rgb(%0,%1,%2);}").arg(r).arg(g).arg(b));
        m_lablist.append(labvalue);

        m_curve->m_plot->addgraph();
        m_curve->m_plot->graph(i)->setcolor(color);
        m_curve->m_plot->graph(i)->setpointcountmax(_pointcount);
        if((i%2)!=0){
            m_curve->m_plot->graph(i)->setaxistype(_tickertype::yaxis_r);
        }else{
            m_curve->m_plot->graph(i)->setaxistype(_tickertype::yaxis_l);
        }
    }

    qvboxlayout *v_layout=new qvboxlayout;
    v_layout->setcontentsmargins(0,0,0,0);
    v_layout->addwidget(m_curve);
    v_layout->addlayout(g_layout);

    ui->centralwidget->setlayout(v_layout);


    for(int i=0;i<_pointcount*0.01;i++){
        slots_timeout();
    }
    isaddok=true;
}

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

void mainwindow::slots_timeout()
{
    double w = (3.14/100)*5;  //w为角速度 ,可以理解为波浪的密度,越大密度越大
    double a = 40;    //  a表示振幅,可以理解为水波的高度,越大高度越高
    static double x;
    x++;
    double wavey = (double)(a * sin(w * x ));// wavey随着x的值改变而改变,从而得到正弦曲线

    static double count=0;
    count+=1;
    qint64 time=qdatetime::currentmsecssinceepoch();
    for(int i=0;i<m_curve->m_plot->getgraphcount();i++)
    {
        int num = qrand()%(200-100)+100;//产生300-500范围的随机岁
        float data=0;//除以10获取 30.0到50.0的随机数
        data+=80*i+num;
//        m_curve->m_plot->graph(i)->adddata(count,data);
        m_curve->m_plot->graph(i)->adddata(count,wavey+80*i);
    }

    if(isaddok)
    {
        if(count>m_curve->m_axisx->ticker()->getrangeend())
        {
            m_curve->m_axisx->ticker()->moverange(count-m_curve->m_axisx->ticker()->getrangeend());
        }
    }
}

void mainwindow::slots_refresh()
{
    m_curve->reupdateall();
}

void mainwindow::slots_updatetrack()
{
    for(int i=0;i<m_curve->m_plot->getgraphcount();i++){
        m_lablist[i]->settext(qstring::number(m_curve->m_plot->graph(i)->gettrackvalue().value,'f',2));
    }
}




源码下载

工程:testcurve
链接: 源码下载

到此这篇关于qt自定义plot实现曲线绘制的文章就介绍到这了,更多相关qt自定义曲线绘制内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关标签: Qt Plot 曲线