QCustomPlot实现实时动态曲线

本文展示了如何在Qt环境中利用QCustomPlot库创建一个实时动态曲线的示例。通过QTimer更新数据,主窗口类MainWindow中定义了设置实时数据的函数setupRealtimeDataDemo,以及添加数据的槽函数realtimeDataSlot。该示例添加了两条曲线,分别对应温度(temp)和湿度(hui),并根据时间戳动态更新和删除数据,以保持横坐标8秒内的数据展示。
摘要由CSDN通过智能技术生成
Qt4中,可以使用QCustompPlot来绘制曲线,QCustompPlot是一个第三方工具,可以到官网下载:http://www.qcustomplot.com/index.php/download
这里实现一个实时动态曲线图,用随机数作为实时数据,程序运行结果如下:

主机环境:fedora9,Qt4.7,Qtcreator 2.0.1
使用Qtcreator 2.0.1新建一个工程,基类模板选择QMainWindow。 将解压得到的QCustompPlot文件夹里面的头文件qcustomplot.h和源文件qcustomplot.cpp复制粘贴到工程文件夹下。 在Qtcreator中,对着工程名右键,添加已有文件,将头文件qcustomplot.h和源文件qcustomplot.cpp都添加到工程中来。
在界面上拖拽一个widget部件,然后升级成Qcustomplot,(参考:http://www.bubuko.com/infodetail-744744.html)部件名称改为customPlot
mainwindow.h代码如下:
 
  1. #ifndef MAINWINDOW_H
  2. #define MAINWINDOW_H
  3.  
  4. #include <QMainWindow>
  5. #include <QTimer>
  6. #include "qcustomplot.h"
  7.  
  8. namespace Ui {
  9.     class MainWindow;
  10. }
  11.  
  12. class MainWindow : public QMainWindow
  13. {
  14.     Q_OBJECT
  15.  
  16. public:
  17.     explicit MainWindow(QWidget *parent = 0);
  18.     ~MainWindow();
  19.     //设置qcustomplot画图属性,实时
  20.     void setupRealtimeDataDemo(QCustomPlot *customPlot);
  21. private slots:
  22.     //添加实时数据槽
  23.     void realtimeDataSlot();
  24.  
  25. private:
  26.     Ui::MainWindow *ui;
  27.     //定时器,周期调用realtimeDataSlot()槽,实现动态数据添加到曲线
  28.     QTimer dataTimer;
  29.  
  30.  
  31. };
  32.  
  33. #endif // MAINWINDOW_H
mainwindow.cpp代码如下:
 
  1. #include "mainwindow.h"
  2. #include "ui_mainwindow.h"
  3. #include <QVector>
  4. #include <QTimer>
  5. #include <QTime>
  6.  
  7.  
  8.  
  9. MainWindow::MainWindow(QWidget *parent) :
  10.     QMainWindow(parent),
  11.     ui(new Ui::MainWindow)
  12. {
  13.     ui->setupUi(this);
  14.  
  15.     setupRealtimeDataDemo(ui->customPlot);
  16.     ui->customPlot->replot();
  17. <
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值