mainwidget.cpp Example File
legendmarkers/mainwidget.cpp
#include "mainwidget.h"
#include <QtCharts/QChart>
#include <QtCharts/QChartView>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QLabel>
#include <QtCore/QDebug>
#include <QtCharts/QLegend>
#include <QtWidgets/QFormLayout>
#include <QtCharts/QLegendMarker>
#include <QtCharts/QLineSeries>
#include <QtCharts/QXYLegendMarker>
#include <QtCore/QtMath>
QT_CHARTS_USE_NAMESPACE
MainWidget::MainWidget(QWidget *parent) :
QWidget(parent)
{
m_chart = new QChart();
m_chartView = new QChartView(m_chart, this);
m_mainLayout = new QGridLayout();
m_mainLayout->addWidget(m_chartView, 0, 1, 3, 1);
setLayout(m_mainLayout);
addSeries();
addSeries();
addSeries();
addSeries();
connectMarkers();
m_chart->setTitle("Legendmarker example (click on legend)");
m_chart->legend()->setVisible(true);
m_chart->legend()->setAlignment(Qt::AlignBottom);
m_chartView->setRenderHint(QPainter::Antialiasing);
}
void MainWidget::addSeries()
{
QLineSeries *series = new QLineSeries();
m_series.append(series);
series->setName(QString("line " + QString::number(m_series.count())));
QList<QPointF> data;
int offset = m_chart->series().count();
for (int i = 0; i < 360; i++) {
qreal x = offset * 20 + i;
data.append(QPointF(i, qSin(qDegreesToRadians(x))));
}
series->append(data);
m_chart->addSeries(series);
if (m_series.count() == 1)
m_chart->createDefaultAxes();
}
void MainWidget::removeSeries()
{
if (m_series.count() > 0) {
QLineSeries *series = m_series.last();
m_chart->removeSeries(series);
m_series.removeLast();
delete series;
}
}
void MainWidget::connectMarkers()
{
const auto markers = m_chart->legend()->markers();
for (QLegendMarker *marker : markers) {
QObject::disconnect(marker, &QLegendMarker::clicked,
this, &MainWidget::handleMarkerClicked);
QObject::connect(marker, &QLegendMarker::clicked, this, &MainWidget::handleMarkerClicked);
}
}
void MainWidget::disconnectMarkers()
{
const auto markers = m_chart->legend()->markers();
for (QLegendMarker *marker : markers) {
QObject::disconnect(marker, &QLegendMarker::clicked,
this, &MainWidget::handleMarkerClicked);
}
}
void MainWidget::handleMarkerClicked()
{
QLegendMarker* marker = qobject_cast<QLegendMarker*> (sender());
Q_ASSERT(marker);
switch (marker->type())
{
case QLegendMarker::LegendMarkerTypeXY:
{
marker->series()->setVisible(!marker->series()->isVisible());
marker->setVisible(true);
qreal alpha = 1.0;
if (!marker->series()->isVisible())
alpha = 0.5;
QColor color;
QBrush brush = marker->labelBrush();
color = brush.color();
color.setAlphaF(alpha);
brush.setColor(color);
marker->setLabelBrush(brush);
brush = marker->brush();
color = brush.color();
color.setAlphaF(alpha);
brush.setColor(color);
marker->setBrush(brush);
QPen pen = marker->pen();
color = pen.color();
color.setAlphaF(alpha);
pen.setColor(color);
marker->setPen(pen);
break;
}
default:
{
qDebug() << "Unknown marker type";
break;
}
}
}