QChart Real Time Plotter

750 Views Asked by At

I am trying to generate a sine wave using QChart and display it on the graph. Actually everything works fine. However, when scrolling the data, sometimes it is very fast, sometimes very slow, even at the beginning of the program, it shows correctly and goes off the screen over time. I couldn't figure out the source of the problem any ideas and suggestions would help me a lot.

Having a timer in my algorithm. When the timer is full, the function depending on 1 more of the x value works and the new point is added to the series. After this process, I try to scroll to a certain extent.

My timer function:

void MyChartView::handleTimeout() {

    m_x += 1;
    m_y = (amplitude * sin(period * (m_x + horizontalShift)) + verticalShift);

    m_series->append(m_x, m_y);

    qDebug() << "New Data -> m_x: " << m_x << " m_y: " << m_y;
    qDebug() << "Plot area width: " << chart->plotArea().width() << " tickCount: " << m_axisX->tickCount();

    if (m_x > 10) {
        chart->scroll(chart->plotArea().width() / m_x, 0);
    }

    this->update();
}

Screenshot:

enter image description here

What I want is to scroll continuously with some space at the end of the data.

Thank you.

1

There are 1 best solutions below

0
jth_92 On

Check out the Dynamic Spline example - https://doc.qt.io/qt-6/qtcharts-dynamicspline-example.html. It initializes the QChart like the following:

Chart::Chart(QGraphicsItem *parent, Qt::WindowFlags wFlags):
QChart(QChart::ChartTypeCartesian, parent, wFlags),
m_series(0),
m_axisX(new QValueAxis()),
m_axisY(new QValueAxis()),
m_step(0),
m_x(5),
m_y(1) {

Then it scrolls based on change (using random number generator):

void Chart::handleTimeout() {
qreal x = plotArea().width() / m_axisX->tickCount();
qreal y = (m_axisX->max() - m_axisX->min()) / m_axisX->tickCount();
m_x += y;
m_y = QRandomGenerator::global()->bounded(10) - 2.5;
m_series->append(m_x, m_y);
scroll(x, 0);
if (m_x == 100)
    m_timer.stop();
}

The m_x() member initializer is what defined how much space to have as data is added. In this instance, there will be a gap of 5 units because the range is 10 units set at m_axisX->setRange(0, 10);. The scroll function essentially scrolls per tick based on plotArea().width() / m_axisX->tickCount();.

So to add space to your chart, just initialize m_x to less than the m_axisX range max.

Also, you should be scrolling based on the ticks count not the m_x.

chart->scroll(chart->plotArea().width() / m_axisX->tickCount(), 0);