一、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;QSplineSeries *series;QChartView *chartview;private slots:void MainWindow::Timeout_handler();
3、.cpp文件添加
using namespace QtCharts;
设置图标标题
chart->setTitle("平均料位");
添加曲线属性
series->setName(tr("Device 1"));
series->setColor(Qt::red);
series->setPen(QPen(Qt::red, 2));
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;QSplineSeries *series;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("平均料位");//曲线属性series->setName(tr("Device 1"));series->setColor(Qt::red);series->setPen(QPen(Qt::red, 2));chart->addSeries(series);//设置X轴属性QValueAxis *axisX = new QValueAxis;chart->addAxis(axisX, Qt::AlignBottom);//axisX->setTickCount(5);axisX->setRange(0, 30);axisX->setTitleText("Time(s)");series->attachAxis(axisX);//设置Y轴属性QValueAxis *axisY = new QValueAxis;chart->addAxis(axisY, Qt::AlignLeft);axisY->setRange(0, 90);axisY->setTitleText("料位");series->attachAxis(axisY);Timeout_handler();//将图标添加到chartview中ui->widget->setChart(chart);
}void MainWindow::Timeout_handler()
{QList<double> data = { 1.2,2.5,5.0,8.3,11.9,13.9,22.9,28.9 };QList<double> data1 = { 12.76, 45.8,64.9,11.9,36.5,74.9,23.9,55.4 };for (int i = 0; i < data.size(); i++){series->append(data.at(i), data1.at(i));}
}
运行结果:
三、绘制动态曲线
使用定时器动态添加数据
QTimer m_timer; // 定时器connect(&m_timer, &QTimer::timeout, this, &MainWindow::Timeout_handler);
m_timer.start(1000);
参考链接 Qt(C++)使用QChart动态显示3个设备的温度变化曲线 - 知乎