Replot function which depends on time, Qt

154 views Asked by At

I'm writing a study project and I need to plot a function that depends on real-time. I used QCustomPlot. This plot should start drawing when I pressed a button. So I've wrote next code

void MainWindow::on_pushButton_restart_clicked()
{
... 
my_timer->restart();
/* Set up and initialize the graph plotting timer */ 
connect(&timer_plot, SIGNAL(timeout()), this, SLOT(realtimePlot())); // where QTimer timer_plot
timer_plot.start(20); 
}

realtimePlot() looks like

void MainWindow::realtimePlot()
{

    ui->widget->graph(0)->data()->clear();

    double key = my_timer->elapsed() / 1000.0;
    static double lastPointKey = 0;

    if(key - lastPointKey > 0.002)
    {
        for (auto& iter : x) {
            ui->widget->graph(0)->addData(iter, sin(iter+key));
        }
        lastPointKey = key;
    }
    ui->widget->replot();
}

And it works properly, but when I want to restart the plot and pressed the button again there is a delay before the plot will be drawn and it increases with each click on the button, and the animation of the plot becomes less and less smooth. Why is this happening and how can I solve it?

Here you can watch my screencast with the problem.

Code for real-time plot I took from here

And MainWindow()

QVector<double> x;
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->widget->addGraph();
    ui->widget->xAxis->setRange(0, 20);
    my_timer->start();
    h = 0.05;
    x.push_back(0);
    for (int i=1; i<=20/h; i++)
    {
        x.push_back(i*h);
    }
}
1

There are 1 answers

0
deethereal On

Well I found the problem. It was my_timer->restart(), but I still don't know why it causes to delay. According to documentation this function just stops and starts the timer.

P.S. Depends on compiler it may not works. For example MinGW doesn't work with this solution unlike clang