QCustomPlot Discussion and Comments

reverse LegendReturn to overview

When I stack my spectra the legend order is oposite to the spectra order. Is there a way to reverse the order of the items in the legend so it remains consistent? I haven't been able to figure it out. Thanks!

You can disable QCustomPlot’s automatic legend insertion and then add the plottables manually in whatever order you want:

customPlot->setAutoAddPlottableToLegend(false);

// Create your graphs/plottables as usual...

for (int i = plottables.size() - 1; i >= 0; --i)
    plottables[i]->addToLegend(customPlot->legend);

This separates the plot creation order from the legend order, so you can simply add the spectra in reverse order to match their visual stacking.

If you want you can also create an addSpectrum method or so, that always adds new legend items at the top:

customPlot->setAutoAddPlottableToLegend(false);

void addSpectrum(...)
{
    QCPGraph *graph = customPlot->addGraph();
    graph->setName(...);
    graph->setData(...);

    auto *item = new QCPPlottableLegendItem(customPlot->legend, graph);

    customPlot->legend->insertRow(0);
    customPlot->legend->addElement(0, 0, item);
}