2

I have a QCustomPlot with multiple graph items on it.

I wish to toggle their visibility by clicking on the relevant item in the legend.

   QObject::connect(
                    plot,
                    &QCustomPlot::legendClick,
                    [](QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event)
                    {
                        // how to get to the relevant graph from the item variable?
                    }
                );

Thank you.

Nik
  • 2,718
  • 23
  • 34

2 Answers2

1

I suggest you try this

     QObject::connect(
                        plot,
                        &QCustomPlot::legendClick,
                        [](QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event)
                        {
                          for (int i=0; i<customPlot->graphCount(); ++i)
                            {
                              QCPGraph *graph = customPlot->graph(i);
                              QCPPlottableLegendItem *itemLegend = customPlot->legend->itemWithPlottable(graph);
                              QCPPlottableLegendItem *plItem = qobject_cast<QCPPlottableLegendItem*>(item);
                              if (itemLegend == plItem )
                                 {
                                 //graph the one you need
                                 }
                             } 
                        };
                    
Vahagn Avagyan
  • 750
  • 4
  • 16
0

A graph's associated legend item is a QCPPlottableLegendItem. So if you cast the abstract legend item to that, you can directly retrieve the plottable (the graph). So you don't need to iterate all graphs as in the other answer:

QCPAbstractLegendItem *yourItem; // the one you get from the event
if (auto plItem = qobject_cast<QCPPlottableLegendItem*>(yourItem))
{
  plItem->plottable()->setVisible(!plItem->plottable()->visible())
  customPlot->replot(); // don't forget to replot
}
DerManu
  • 702
  • 4
  • 12