QtCharts Legend 点击选择demo

Qwt 上有专门的类QwtLegend来实现legend图标滴点击选中,QtCharts上没有现成的类来实现,copy qtcharts example(legendmarkers)。代码如下:

void MainWindow::MarkersConnect(QChart *poChart)
{
    /* Connect all markers to handler */
    foreach (QLegendMarker* poLegendMarker, poChart->legend()->markers())
    {
        /* Disconnect possible existing connection to avoid multiple connections */
        QObject::disconnect(poLegendMarker, SIGNAL(clicked()), this, SLOT(HandleMarkerClicked()));
        QObject::connect(poLegendMarker, SIGNAL(clicked()), this, SLOT(HandleMarkerClicked()));
    }
}

void MainWindow::HandleMarkerClicked()
{
    QLegendMarker* poLegendMarker = qobject_cast (sender());
    Q_ASSERT(poLegendMarker);

    switch (poLegendMarker->type())
    {
        case QLegendMarker::LegendMarkerTypeXY:
        {
        /* Toggle visibility of Series */
        poLegendMarker->series()->setVisible(!poLegendMarker->series()->isVisible());

        /* Turn legend marker back to visible,
         * since hiding poSeries also hides the marker
         * and we don't want it to happen now. */
        poLegendMarker->setVisible(true);

        /* Dim the marker, if series is not visible */
        qreal alpha = 1.0;

        if (!poLegendMarker->series()->isVisible())
        {
            alpha = 0.5;
        }

        QColor oColor;
        QBrush oBrush = poLegendMarker->labelBrush();
        oColor = oBrush.color();
        oColor.setAlphaF(alpha);
        oBrush.setColor(oColor);
        poLegendMarker->setLabelBrush(oBrush);

        oBrush = poLegendMarker->brush();
        oColor = oBrush.color();
        oColor.setAlphaF(alpha);
        oBrush.setColor(oColor);
        poLegendMarker->setBrush(oBrush);

        QPen oPen = poLegendMarker->pen();
        oColor = oPen.color();
        oColor.setAlphaF(alpha);
        oPen.setColor(oColor);
        poLegendMarker->setPen(oPen);

        break;
        }
    default:
        {
        qDebug() << "Unknown poLegendMarker type";
        break;
        }
    }
}


你可能感兴趣的:(QT,Qt,Charts,QtCharts,legend)