qcustomplot 是一个基于 qt 框架的轻量级 c++ 绘图库,专为高效绘制二维图表(如曲线图、柱状图、金融图表等)而设计。相比 qt charts 模块,它以 高性能 和 高度可定制性 著称,尤其适合需要实时数据可视化的科学计算、工业监控和金融分析场景。
核心特性概览
特性 | 说明 |
---|---|
轻量高效 | 仅需 2 个头文件 + 1 个源码文件,零外部依赖 |
实时性能 | 优化处理百万级数据点,支持 opengl 加速 |
多图层系统 | 支持无限图层叠加,独立坐标系 |
交互功能 | 内置缩放/平移/选择/图例拖拽等操作 |
丰富图元 | 提供 20+ 可交互绘图元素(箭头、文本、追踪线等) |
导出格式 | 支持 png/jpeg/pdf/svg 矢量导出 |
跨平台 | 兼容 windows/macos/linux/嵌入式系统 |
核心组件解析
1.绘图核心 (qcustomplot类)
qcustomplot *plot = new qcustomplot(parent);
坐标系系统:支持多轴(x/y/顶部/右侧轴)
图层管理:通过
qcplayer
实现元素分层渲染事件处理:鼠标/键盘交互事件接口
2.数据容器 (qcpdatacontainer)
qvector<double> x(100), y(100); // 填充数据... qcpgraph *graph = plot->addgraph(); graph->setdata(x, y);
内存优化:使用
qsharedpointer
管理大数据数据操作:支持数据排序、范围筛选、nan 处理
3.核心图元类型
图元类型 | 说明 | 创建方法 |
---|---|---|
qcpgraph | 曲线图 | addgraph() |
qcpbars | 柱状图 | new qcpbars(xaxis, yaxis) |
qcpcolormap | 热力图 | addcolormap() |
qcpfinancial | k线图 | new qcpfinancial(xaxis, yaxis) |
qcpitem* | 交互元素 | new qcpitemline(plot) |
4.交互元素示例
// 创建数据追踪器 qcpitemtracer *tracer = new qcpitemtracer(plot); tracer->setgraph(graph); tracer->setgraphkey(5.0); // 定位到x=5.0的点 // 添加十字坐标线 qcpitemstraightline *vline = new qcpitemstraightline(plot); vline->point1->setcoords(5, 0); // (x,y) vline->point2->setcoords(5, 10);
基础使用示例
1. 创建简单曲线图
// 创建绘图区域 qcustomplot *plot = new qcustomplot(this); // 生成数据 qvector<double> x(101), y(101); for (int i=0; i<101; ++i) { x[i] = i/50.0 - 1; // -1 到 1 y[i] = x[i]*x[i]; // y = x² } // 添加曲线 plot->addgraph(); plot->graph(0)->setdata(x, y); // 设置坐标轴 plot->xaxis->setlabel("x axis"); plot->yaxis->setlabel("y axis"); plot->rescaleaxes(); // 重绘 plot->replot();
2. 实时数据更新
// 定时更新数据 qtimer *timer = new qtimer(this); connect(timer, &qtimer::timeout, [&]() { static double t = 0; plot->graph(0)->adddata(t, qsin(t)); // 追加新数据点 plot->xaxis->setrange(t-10, t); // 滚动x轴 plot->replot(); t += 0.1; }); timer->start(50); // 20 fps刷新
高级功能演示
1. 多图层混合
// 主图层:曲线图 plot->addgraph(); // 创建新图层(在顶部显示标注) qcplayer *annolayer = new qcplayer(plot, "annotations"); plot->addlayer("annotations", 0, qcustomplot::limabove); // 置于顶层 // 在标注层添加文本 qcpitemtext *textlabel = new qcpitemtext(plot); textlabel->setlayer(annolayer); textlabel->position->setcoords(5, 8); textlabel->settext("峰值区域");
2. 自定义绘图元素
// 创建自定义彩色柱状图 qcpbars *bars = new qcpbars(plot->xaxis, plot->yaxis); // 渐变着色 qvector<qcolor> colors = {qt::blue, qt::green, qt::red}; qsharedpointer<qcpcolorgradient> gradient(new qcpcolorgradient); gradient->setcolorstops({ {0, qt::blue}, {0.5, qt::green}, {1, qt::red} }); // 应用着色 bars->setbrush(qbrush(*gradient));
性能优化技巧
数据分块加载
graph->setlinestyle(qcpgraph::lsnone); // 禁用连线 graph->setscatterstyle(qcpscatterstyle::ssdot); // 仅绘制点
opengl 加速
plot->setopengl(true); // 启用gpu渲染
增量数据更新
// 仅追加新数据(避免全量重设) graph->adddata(newx, newy); graph->data()->removebefore(newx-visiblerange);
异步重绘
plot->setreplottime(20); // 限制重绘频率(ms)
到此这篇关于qt qcustomplot库简介的文章就介绍到这了,更多相关qt qcustomplot库内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论