c++qtqt5qchartqchartview

QAbstractSeries signal clicked because type is QLineSeries


Is there a way to connect QAbstractSeries to a clicked signal because the type of the QAbstractSeries is a QLineSeries?

I can do the following:

QlineSeries *series = new QLineSeries();
QChart *chart = new QChart();
series->append(1,1);
chart->addSeries(series);
connect(series, &QLineSeries::clicked, this, &View::myFunction);

But if i have defined the series in another class and i can only access the series through

QList<QAbstractSeries*> seriesList = chart->series();

I cannot connect a series through

connect(seriesList[0], &QAbstractSeries::clicked, this, &View::myFunction);

because QAbstractSeries has not a signal "clicked". But i can access the type through

seriesList[0].type();

But now i don't know how to handle the connection with this information. Or is there another way to get the series out of my chart as a QLineSeries?


Solution

  • The clicked signal is associated with the objects of the class QXYSeries and their derivatives such as QLineSeries so the solution is to make a casting to filter the series:

    for(QAbstractSeries* series: chart->series()){
        if(QXYSeries* xyseries = qobject_cast<QXYSeries *>(series)){
            connect(xyseries, &QXYSeries::clicked, this, &View::myFunction);
        }
    }
    

    With the previous code they will be applied to the classes derived from QXYSeries such as QLineSeries and QScatterSeries, but if you only want to apply to QLineSeries then you must do the following:

    for(QAbstractSeries* series: chart->series()){
        if(QLineSeries* lineseries = qobject_cast<QLineSeries *>(series)){
            connect(lineseries, &QLineSeries::clicked, this, &View::myFunction);
        }
    }