You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Qt中已废弃的QTime::elapsed()如何替代以实现QCustomPlot实时绘制sin(t)

替代方案

Qt官方推荐使用QElapsedTimer类替代已废弃的QTime::elapsed()实现相同的计时功能,该类专门用于短时间间隔计算,精度更高,也不会出现QTime跨天计时错误、受系统时间调整影响的问题。

修改后的代码如下:

void MainWindow::realtimePlot()
{
    static QElapsedTimer timer;
    // 首次调用时启动计时器
    if (!timer.isValid()) {
        timer.start();
    }
    // elapsed()返回毫秒值,除以1000转成秒,和原有逻辑完全兼容
    double key = timer.elapsed() / 1000.0;
    QTextStream(stdout) << (key);
    static double lastPointKey = 0;
    if(key - lastPointKey > 0.002)
    {
        ui->widget->graph(0)->addData(key, sin(key));
        lastPointKey = key;
    }

    ui->widget->graph(0)->rescaleValueAxis();
    ui->widget->xAxis->setRange(key, 4, Qt::AlignRight);
    ui->widget->replot();
}

补充说明:

  • QElapsedTimer的elapsed()方法返回值格式和原QTime::elapsed()完全一致,原有单位转换、间隔判断逻辑不需要做任何调整
  • 该类默认调用系统最高精度的计时接口,实时绘图的时间轴稳定性会优于旧实现

内容的提问来源于stack exchange,提问作者deethereal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 10:18:03