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->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->end->setCoords(4, 1.6); // point to (4, 1.6) in x-y-plot coordinates

  // 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


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

private slots:
  void simpleItemSlot();
  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!

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);