0

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);
    }
}
deethereal
  • 53
  • 1
  • 12
  • Please create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Ghasem Ramezani Sep 14 '21 at 10:14
  • @GhasemRamezani I added code for MainWindow, the truth is that I don't know how a minimal reproducible example for QtApp should look – deethereal Sep 14 '21 at 14:06
  • @deethereal Then read the links – eyllanesc Sep 14 '21 at 14:46
  • @eyllanesc I've read it but for "reproducible" example QtApp requires at least 6 standard files, I've provided all code, that I use except for mainwindow.h, mainwindow.ui and main.cpp. I also recorded and shared a video with the problem. Is there not enough information? – deethereal Sep 14 '21 at 15:04
  • 1
    Why do you connect the timer when the button is pressed? I would expect that the wiring is done initially on creation. Then the button should only start the timer. – ypnos Sep 14 '21 at 21:57
  • @ypnos Yeap, that was not logically correct, thank you for your note – deethereal Sep 15 '21 at 06:55

1 Answers1

0

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

deethereal
  • 53
  • 1
  • 12