Qt-在Qt的工程中使用第三方组件QCustomPlot实现chart功能
#include "qcustomplot.h"
// 1. 创建实例
QCustomPlot *customPlot = new QCustomPlot(this);
// 2. 添加到布局 (假设主布局为 verticalLayout)
verticalLayout->addWidget(customPlot);
// 3. 基本美化 (可选)
customPlot->setBackground(QColor(240, 240, 240)); // 设置背景色
customPlot->axisRect()->insetLayout()->setInsetAlignment(0, Qt::AlignTop|Qt::AlignRight); // 图例位置
1. 折线图 (最常用,如轨迹、趋势)
// 生成数据
QVector<double> x(101), y(101);
for (int i=0; i<101; ++i) {
x[i] = i/50.0 - 1; // x从-1到1
y[i] = x[i]*x[i]; // y=x^2
}
// 添加图形
customPlot->addGraph();
customPlot->graph(0)->setData(x, y);
// 设置样式
customPlot->graph(0)->setName("抛物线");
customPlot->graph(0)->setPen(QPen(Qt::blue, 2)); // 蓝色,线宽2
// 设置坐标轴标签
customPlot->xAxis->setLabel("时间 (s)");
customPlot->yAxis->setLabel("数值");
// 自动调整坐标轴范围以适配数据
customPlot->rescaleAxes();
customPlot->replot(); // 刷新绘制
2. 散点图 (如雷达点迹)
customPlot->addGraph();
customPlot->graph(0)->setLineStyle(QCPGraph::lsNone); // 无线条
customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 6)); // 圆点,大小6
// 设置数据
QVector<double> xData = {1.0, 2.0, 3.0, 4.0};
QVector<double> yData = {2.0, 4.0, 1.0, 5.0};
customPlot->graph(0)->setData(xData, yData);
customPlot->rescaleAxes();
customPlot->replot();
3. 柱状图 (如统计评估)
QCPBars *bars = new QCPBars(customPlot->xAxis, customPlot->yAxis);
bars->setWidth(0.5); // 柱子宽度
bars->setData({1, 2, 3}, {10, 20, 15}); // x值, y值
bars->setPen(Qt::NoPen);
bars->setBrush(QColor(10, 140, 70, 180)); // 绿色半透明
customPlot->rescaleAxes();
customPlot->replot();
三、 动态更新数据 (实时仿真关键)
// 假设 m_graph 是成员变量,在初始化时获取:
// m_graph = customPlot->addGraph();
void updatePlot(double newX, double newY) {
// 1. 追加数据
m_graph->addData(newX, newY);
// 2. 限制数据点数 (防止内存溢出,例如只保留最近1000个点)
if (m_graph->dataCount() > 1000) {
m_graph->removeDataBefore(newX - 10.0); // 移除旧数据
}
// 3. 动态调整坐标轴 (可选:让视图跟随数据移动)
customPlot->xAxis->setRange(newX - 10, newX); // 显示最近10秒
customPlot->yAxis->rescale(true); // 重新缩放Y轴
// 4. 刷新
customPlot->replot(QCustomPlot::rpQueuedReplot); // 使用队列刷新,提高性能
}
四、 交互功能
// 启用拖拽缩放
customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom);
// 启用图例点击隐藏/显示
connect(customPlot, &QCustomPlot::legendClick, this, [this](QCPAbstractLegendItem *item, bool event) {
if (QCPPlottableLegendItem *plItem = qobject_cast<QCPPlottableLegendItem*>(item)) {
plItem->plottable()->setVisible(!plItem->plottable()->visible());
customPlot->replot();
}
});
五、 导出图片
// 导出为 PNG
customPlot->savePng("plot.png", 800, 600);
// 导出为 PDF (需要 Qt::PrintSupport)
customPlot->savePdf("plot.pdf");
性能优化:
如果数据点极多(>10万),启用 customPlot->graph(0)->setAntialiased(false); 关闭抗锯齿以提高速度。
使用 rpQueuedReplot 而不是直接 replot(),避免频繁重绘导致界面卡顿。
内存管理:如果插件会被多次加载/卸载,确保在析构函数中正确删除 QCustomPlot 指针,防止内存泄漏。
欢迎关注我,一起进步!扫描下方二维码即可加我
浙公网安备 33010602011771号