QCustomPlot横坐标为毫秒级的时间轴数据展示的实时刷新数据功能

文章描述了一个使用C++和Qt库开发的Widget类,其中包含实时数据处理和图形显示功能,使用QTimer定时更新数据并调整x轴和y轴范围。
摘要由CSDN通过智能技术生成

在这里插入图片描述
头文件

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QTimer>

QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();
    int realtimeDataSlot();
private:
    Ui::Widget *ui;
    QTimer* dataTimer;
};
#endif // WIDGET_H

源文件

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    dataTimer = new QTimer(this);

    ui->customPlot->addGraph();
    ui->customPlot->graph(0)->setPen(QPen(QColor(40, 110, 255)));

    //设置x轴格式
    QSharedPointer<QCPAxisTickerTime> timeTicker(new QCPAxisTickerTime);
    //设置tick个数
    timeTicker->setTickCount(10);
    //毫秒为单位
    timeTicker->setTimeFormat("%h:%m:%s.%z");
    ui->customPlot->xAxis->setTicker(timeTicker);
    ui->customPlot->axisRect()->setupFullAxesBox();
    //设置Y轴的范围
    ui->customPlot->yAxis->setRange(-1, 1);


    //设置x轴为当前时间
    int nowtime = QTime::currentTime().msecsSinceStartOfDay(); //获取精度为毫秒
    double key = nowtime;
    //设置初始坐标轴的x坐标
    ui->customPlot->xAxis->setRange(key * 0.001, 10, Qt::AlignRight);

    connect(dataTimer, &QTimer::timeout, this, &Widget::realtimeDataSlot);
    dataTimer->start(0);
}

Widget::~Widget()
{
    delete ui;
}

int Widget::realtimeDataSlot()
{
    //key, 8, Qt::AlignRight
    int nowtime = QTime::currentTime().msecsSinceStartOfDay();
    double key = nowtime;

    static double lastPointKey;
    //记录每次刷新数据的时候添加点的个数,此处只想知道时钟滴答准确性,没什么作用
    static int dataCount;
    if (key - lastPointKey >= 2) //两毫秒保存一个数据
    {
        //产生随机数,注意此处只是把x轴转为秒为单位展示,实际上还是毫秒级别
        ui->customPlot->graph(0)->addData(key*0.001, QRandomGenerator::global()->bounded(110));
        lastPointKey = key;
        dataCount++;
    }

    static double lastMoveKey;
    //下面的逻辑要基于自己的想法实现,主要是多少秒刷一次x轴和移动坐标轴的问题,我的想法是一秒移动一次
    if(key - lastMoveKey >= 1000){
        ui->customPlot->xAxis->setRange(key*0.001, 10, Qt::AlignRight);  //注意此处设置key点在最右侧
        //此处需要删除10秒前的数据
        ui->customPlot->graph(0)->data()->removeBefore(key*0.001-10);
        lastMoveKey = key;

        qDebug() << dataCount;
         dataCount=0;
    }

    //y轴自适应
    ui->customPlot->graph(0)->rescaleValueAxis();
    ui->customPlot->replot();
    return 0;
}

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_小白鱼儿_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值