How to toggle a QCustomPlot graph's visibility by clicking on the legend

561 views Asked by At

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.

2

There are 2 answers

0
Vahagn Avagyan On BEST ANSWER

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
                                 }
                             } 
                        };
                    
0
DerManu On

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
}