原文链接:C++ Qt开发:Charts折线图绑定事件-腾讯云开发者社区-腾讯云
// 设置图表的主题
m_chart->setTheme(QChart::ChartThemeBlueNcs);
QLegend *legend = m_chart->legend();
legend->setAlignment(Qt::AlignTop); // 设置图例的位置为底部
legend->setVisible(true); // 显示图例
legend->setBorderColor(Qt::black); // 设置图例边框颜色
// 显示或隐藏图例对应的折线
foreach (QLegendMarker *marker, legend->markers())
{
connect(marker,&QLegendMarker::clicked,this,[&](){
qDebug() <<"点击图例:";
// 将发送者强制转换为 QLegendMarker 类型
QLegendMarker* marker = qobject_cast<QLegendMarker*>(sender());
// 检查标记的类型
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:
break;
}
});
}