QT 动态实时曲线
1.首先在工程文件中加入
QT += charts
2. .h文件
1 #ifndef WIDGET_H 2 #define WIDGET_H 3 4 #include <QWidget> 5 #include <QPen> 6 #include <QPainter> 7 #include <QtSvg/QSvgWidget> 8 #include <QtSvg/QSvgRenderer> 9 #include <QMouseEvent> 10 11 #include <QtCharts> 12 using namespace QtCharts; 13 namespace Ui { 14 class Widget; 15 } 16 17 class Widget : public QWidget 18 { 19 Q_OBJECT 20 21 public: 22 explicit Widget(QWidget *parent = 0); 23 ~Widget(); 24 25 private slots: 26 protected: 27 void timerEvent(QTimerEvent *event) Q_DECL_OVERRIDE; 28 private: 29 Ui::Widget *ui; 30 void dataReceived(int value); 31 int timerId; 32 int maxSize; // data 最多存储 maxSize 个元素 33 int maxX; 34 int maxY; 35 QList<double> data; // 存储业务数据的 list 36 QChart *chart; 37 QChartView *chartView; 38 QSplineSeries *splineSeries; 39 QScatterSeries *scatterSeries; 40 41 42 }; 43 44 #endif // WIDGET_H
3..cpp文件
1 #include "widget.h" 2 #include "ui_widget.h" 3 #include <QDebug> 4 Widget::Widget(QWidget *parent) : 5 QWidget(parent), 6 ui(new Ui::Widget) 7 { 8 ui->setupUi(this); 9 maxSize = 31; // 只存储最新的 31 个数据 10 maxX = 300; 11 maxY = 100; 12 splineSeries = new QSplineSeries(); 13 scatterSeries = new QScatterSeries(); 14 scatterSeries->setMarkerSize(8); 15 16 17 chart = new QChart(); 18 chart->addSeries(splineSeries); 19 chart->addSeries(scatterSeries); 20 chart->legend()->hide(); 21 chart->setTitle("实时动态曲线"); 22 chart->createDefaultAxes(); 23 chart->axisX()->setRange(0, 300); 24 chart->axisY()->setRange(0, maxY); 25 chartView = new QChartView(chart); 26 27 QValueAxis *axisx = new QValueAxis; 28 axisx->setGridLineVisible(false); 29 axisx->setTitleText("sample time(s)"); 30 chartView->chart()->setAxisX(axisx, splineSeries); 31 32 QValueAxis *axisy = new QValueAxis; 33 axisy->setGridLineVisible(false); 34 axisy->setTitleText("height(meter)"); 35 chartView->chart()->setAxisY(axisy,splineSeries); 36 37 chartView->setRenderHint(QPainter::Antialiasing); 38 39 40 QHBoxLayout *layout = new QHBoxLayout(); 41 layout->setContentsMargins(0, 0, 0, 0); 42 layout->addWidget(chartView); 43 setLayout(layout); 44 timerId = startTimer(200); 45 qsrand(QDateTime::currentDateTime().toTime_t()); 46 } 47 48 Widget::~Widget() 49 { 50 delete ui; 51 } 52 53 void Widget::timerEvent(QTimerEvent *event) { 54 // 产生一个数据,模拟不停的接收到新数据 55 if (event->timerId() == timerId) { 56 int newData = qrand() % (maxY + 1); 57 dataReceived(newData); 58 } 59 } 60 61 void Widget::dataReceived(int value) { 62 data << value; 63 // 数据个数超过了最大数量,则删除所有数据,从头开始。 64 while (data.size() > maxSize) { 65 data.clear(); 66 67 } 68 // 界面被隐藏后就没有必要绘制数据的曲线了 69 if (isVisible()) { 70 splineSeries->clear(); 71 scatterSeries->clear(); 72 int dx = maxX / (maxSize-1); 73 for (int i = 0; i < data.size(); ++i) { 74 splineSeries->append(i*dx, data.at(i)); 75 scatterSeries->append(i*dx, data.at(i)); 76 } 77 } 78 }
实现结果