QCustomPlot Discussion and Comments

Mark graph by click on its legend item!?Return to overview

Hi guys,

i try to select the graph that is selected by clicking on its legend item... at the Moment, i react to the legendClick() Signal of legend

connect(ui->plotter, SIGNAL(legendClick(QCPLegend*,QCPAbstractLegendItem*,QMouseEvent*)), 
    this, SLOT(plotterLegendClick(QCPLegend*,QCPAbstractLegendItem*,QMouseEvent*)));

Inside the SLOT, i try to find the graph by its Name:

void MainWindow::plotterLegendClick(QCPLegend *l, QCPAbstractLegendItem *ai, QMouseEvent *me)
{
    for(int i=0; i<l->parentPlot()->graphCount(); i++)
    {
        if(l->parentPlot()->graph(i)->name() == ((QCPPlottableLegendItem*)ai)->plottable()->name())
        {
            l->parentPlot()->graph(i)->setSelected(!l->parentPlot()->graph(i)->selected());
            ui->statusBar->showMessage("Selected Graph: \"" + l->parentPlot()->graph(i)->name() + "\"");
        }
        else
        {
            l->parentPlot()->graph(i)->setSelected(false);
        }
    }
}

It seems that there is a Problem with the casting of ((QCPPlottableLegendItem*)ai).

Is it possible to check whether ai is of type QCPPlottableLegendItem? Or is there another, better way to do this?

Hi Taneeda

Sorry to hijack your thread. Did you ever find a solution for your other issue?

http://www.qcustomplot.com/index.php/support/forum/148

Thanks!

No Problem :) Sorry, i hasn't tried this anymore since the creation of the thread...

I found a solution for my Problem with marking a graph when selecting its legend entry:

void MainWindow::plotterLegendClick(QCPLegend *l, QCPAbstractLegendItem *ai, QMouseEvent *me)
{
    Q_UNUSED(me);

    if(NULL != l && NULL != ai)
    {
        // Check for selection
        if("QCPPlottableLegendItem" == QString(ai->metaObject()->className()))
        {
            ....
        }
    }
}

Now it works fine :)

The typical C++-way of checking whether it's the right child class is to see if a dynamic cast succeeds, i.e.:

QCPPlottableLegendItem *legendItem;
if((legendItem = dynamic_cast<QCPPlottableLegendItem*>(ai)))
{ /* ai is a plottable legend item */ }

Two quick comments:
1. The interaction example shows how it's done. There you have the asked for behaviour that legend and plottable selection is synchronized.

2. Taneeda your method in your previous post is a bit strange, and Jonas has pointed out the correct C++ way with dynamic_cast (except for the double-bracket in the if condition, I guess that's by accident). I'd now like to point out the correct Qt way to do it: Use qobject_cast instead of dynamic_cast. It does the same thing but is much faster than dynamic_cast. And most QCustomPlot classes derive from QObject, so they can be used with qobject_cast.