QCustomPlot Discussion and Comments

Cannot remove graph is it contains no dataReturn to overview

In your interaction-example, edit the addRandomGraph function in this way:

  ui->customPlot->addGraph();
  ui->customPlot->graph()->setName(QString("New graph %1").arg(ui->customPlot->graphCount()-1));
  //ui->customPlot->graph()->setData(x, y);
  ui->customPlot->graph()->setLineStyle((QCPGraph::LineStyle)(rand()%5+1));

When you run it, you will still have 4 random graph, which their names shown in the legend but with no data.
Now, select a graph in the legend and right-click to show the context menu. You will see the "Remove selected graph" item is missing.
This is because customPlot->selectedGraphs().size() is 0.

How to remove a graph that contains no data? It actually exists because it is shown in the legend...

It's not entirely unintended that a graph with no data points can't be selected. After all, there are no data points to be selected.

Is there a specific reason you want to have an empty graph in your plot? (The interaction example never leads to this case, you've modified addRandomGraph that now leads to empty graphs.)

Anyhow, the right way to go about this would be to change the removeSelectedGraph method and not look at the selectedGraphs() to find the ones to delete, but to use ui->customPlot->legend->selectedItems() and use those to decide which to delete. Make sure to buffer the list and iterate from the back so you don't delete elements before other elements which are yet to be iterated over. You'll then want to qobject_cast the returned abstract legend item to a QCPPlottableLegendItem, which provides you with the plottable through legendItem->plottable(). This you can pass to customPlot->removePlottable(). Watch out, after this, the legendItem pointer will be dangling and shouldn't be used anymore.