一、QChart简介
QChart是Qt中专门用于绘制图表的模块,支持折线图、柱状图、饼图等常见类型。其主要组成部分有:
- QChart:整个图表的容器,管理图表中的所有数据和图形属性
- QChartView:继承自QGraphicsView,用于显示QChart,并且支持缩放和平移等交互操作
- QLineSeries:折线图数据的容器,用于存储和绘制点之间的连线
- QValueAxis:坐标轴组件,用于显示坐标轴的标签和刻度线
二、绘制动态曲线
1、QT项目pro文件中添加charts
2、.h文件添加库文件
#include <QtCharts>
注:要放在最前面,不然会报一些莫名其妙的错误。
#include <QtCharts>
#include <QtCharts/qsplineseries.h>private:QChart *chart;QTimer m_timer; // 定时器QSplineSeries *series;QChartView *chartview;int m_timeCount; //时间计数private slots:void MainWindow::Timeout_handler();
3、.cpp文件添加
using namespace QtCharts;
设置图标标题
chart->setTitle("平均料位");
添加曲线属性
chart->addSeries(series);
设置X轴、Y轴属性
//设置X轴属性
QValueAxis *axisX = new QValueAxis;
chart->addAxis(axisX, Qt::AlignBottom);
axisX->setRange(0, 60);
axisX->setTitleText("Time(s)");
series->attachAxis(axisX);//设置Y轴属性
QValueAxis *axisY = new QValueAxis;
chart->addAxis(axisY, Qt::AlignLeft);
axisY->setRange(0, 60);
axisY->setTitleText("料位");
series->attachAxis(axisY);
4、拖入Widget控件,提升为QChartView控件
将图标添加到chartview中
ui->widget->setChart(chart);
5、完整示例代码
mainwindow.h
#include <QtCharts>
#include <QtCharts/qsplineseries.h>QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACEclass MainWindow : public QMainWindow
{Q_OBJECTprivate:Ui::MainWindow *ui;QChart *chart;QTimer m_timer; // 定时器QSplineSeries *series;int m_timeCount; //时间计数QChartView *chartview;private slots:void MainWindow::Timeout_handler();
}
mainwindow.cpp
#include <QtSerialPort/qserialport.h>
#include <QtSerialPort/qserialportinfo.h>using namespace QtCharts;MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow)
{ui->setupUi(this);chart = new QChart();series = new QSplineSeries();chartview = new QChartView();//设置图标标题chart->setTitle("平均料位");//曲线属性chart->addSeries(series);//设置X轴属性QValueAxis *axisX = new QValueAxis;chart->addAxis(axisX, Qt::AlignBottom);//axisX->setTickCount(5);axisX->setRange(0, 60);axisX->setTitleText("Time(s)");series->attachAxis(axisX);//设置Y轴属性QValueAxis *axisY = new QValueAxis;chart->addAxis(axisY, Qt::AlignLeft);axisY->setRange(0, 60);axisY->setTitleText("料位");series->attachAxis(axisY);m_timeCount = 0;connect(&m_timer, &QTimer::timeout, this, &MainWindow::Timeout_handler);m_timer.start(1000);//将图标添加到chartview中ui->widget->setChart(chart);
}void MainWindow::Timeout_handler()
{// 更新时间计数m_timeCount++;QPointF p1(m_timeCount, qrand() % 10 + 20);series->append(p1);// 清除多余的点,只保留最新的30个数据点if (series->count() > 30) {series->removePoints(0, 1);}
}
运行结果: