QCustomPlot Discussion and Comments

Plotting from different functionsReturn to overview

I have one function where I plot my graph, like this:

ui->widget->addGraph();
ui->widget->xAxis->setRange(QCPRange(0, b.size()));
ui->widget->yAxis->setRange(QCPRange(-10, 10));
ui->widget->graph(0)->setPen(QPen(Qt::blue));
ui->widget->graph(0)->setBrush(QBrush(Qt::blue));
ui->widget->graph(0)->setData(a,b);
ui->widget->replot();

And at the end of that function I'm calling other function which should add new plot (keep the previous one) but first time it writes over that first plot (deletes the first plot) and the second time program crashes:

ui->widget->addGraph();
ui->widget->graph(1)->setPen(QPen(Qt::red));
ui->widget->graph(1)->setBrush(QBrush(Qt::green));
ui->widget->graph(1)->setData(a,b);
ui->widget->replot();

Hi,

It is recommended to save the return value of addGraph (which is a pointer to the QCPGraph), ideally in the smart pointer QPointer so you can safely access it later. The way you do it, by index, is only for very simple programs and in order to be able to do quick prototypes. At least, you should be checking the graphCount value so you don't get out-of-bounds issues.

Note that QCustomPlot maintains ownership of the plottables, so you must not delete the graph pointer manually.

Other than that, I don't see a problem with your code. Why do you think the first graph is deleted? Is it maybe just hidden by the second one because you give it the same data (a, b)?

I've made a mistake as I was writing that question. When its like that, it crashes immediately with error: class QCPGraph *__thiscall QCustomPlot::graph(int) const index out of bounds: 1 . And when I write for both graph(0) it does what I wrote above.

They are the same plot (they have the same data), I wrote it so the first plot draws my plot right away and the other plot can go over the first one and color the it time by time. Both of them work perfect when I start them separately, but when I try to draw them in the same widget, thats where problems start.

Also, if you mean something like this:

myPlot = new QCustomPlot(ui->widget);
myPlot->addGraph();
myPlot->graph(0)->setPen(QPen(Qt::blue));
.
.
.

It doesnt work for me,, widget is empty and I dont know why.