QCustomPlot Discussion and Comments

qt crashes when updating QCPItemText and call replot() to make it realtimeReturn to overview

Dear all,

I am new to QCustomPlot and trying to updating text item in real time in a plot. I used official examples of Version: 2.0.0 in the download page (http://qcustomplot.com/index.php/download) and modified the setupSimpleItemDemo(QCustomPlot *customPlot) function in mainwindow.cpp as shown below:

void MainWindow::setupSimpleItemDemo(QCustomPlot *customPlot)
{
  demoName = "Simple Item Demo";
  customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom);
  
  // add the text label at the top:
  QCPItemText *textLabel = new QCPItemText(customPlot);
  textLabel->setPositionAlignment(Qt::AlignTop|Qt::AlignHCenter);
  textLabel->position->setType(QCPItemPosition::ptAxisRectRatio);
  textLabel->position->setCoords(0.5, 0); // place position at center/top of axis rect
  textLabel->setText("Text Item Demo");
  textLabel->setFont(QFont(font().family(), 16)); // make font a bit larger
  textLabel->setPen(QPen(Qt::black)); // show black border around text
  
  // add the arrow:
  QCPItemLine *arrow = new QCPItemLine(customPlot);
  arrow->start->setParentAnchor(textLabel->bottom);
  arrow->end->setCoords(4, 1.6); // point to (4, 1.6) in x-y-plot coordinates
  arrow->setHead(QCPLineEnding::esSpikeArrow);

  // setup a timer that repeatedly calls MainWindow::realtimeDataSlot:
  connect(&dataTimer, SIGNAL(timeout()), this, SLOT(simpleItemSlot()));
  dataTimer.start(0); // Interval 0 means to refresh as fast as possible
}

simpleItemSlot is:

void MainWindow::simpleItemSlot()
{
    static QTime time(QTime::currentTime());
    // calculate two new data points:
    double key = time.elapsed()/1000.0; // time elapsed since start of demo, in seconds
    textLabel->setText(QString::number(key));

    ui->customPlot->replot();
}

And I have already defined textLabel and simpleItemSlot in mainwindow.h

private slots:
  void simpleItemSlot();
private:
  QCPItemText *textLabel;

The project can be built but every time I run it, qt crashes and stops working, can anyone help me with it?

Thanks a lot!
Juan

In your simpleItemSlot, the textLabel is never initialized and thus you dereference an invalid pointer. Your compiler should be warning about use of uninitialized variables...

Ah, yes!

I shouldn't re-declare it. just

textLabel = new QCPItemText(customPlot);