Search code examples
c++qtqcustomplot

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


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.


Solution

  • 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
                                     }
                                 } 
                            };