目的:介绍Qt中图表可以达到的一些效果,可以把我们的项目做的高大上。
此博文主要介绍图表说明Legend的一些设置,来源示例Legend和LegendMarker,位于\Examples\Qt-5.9.4\charts\
Legend主要实现对图表说明的编辑,添加删除Bar,图表说明的位置,以及图表说明字体的设置
LegendMarker主要实现图表说明与图表的对应关系,点击图表说明可以显示/隐藏相应的图表,上面图中隐藏了line1和line3
1. 放置位置
附着图表 m_chart->legend()->attachToChart();
不附着图表 m_chart->legend()->detachFromChart();
位于图表上方 m_chart->legend()->setAlignment(Qt::AlignTop);
位于图表下方 m_chart->legend()->setAlignment(Qt::AlignBottom);
位于图表左侧 m_chart->legend()->setAlignment(Qt::AlignLeft);
位于图表右侧 m_chart->legend()->setAlignment(Qt::AlignRight);
2. 设置字体
1 QFont font = m_chart->legend()->font();
2 font.setBold(!font.bold());//是否加粗
3 font.setItalic(!font.italic());//是否斜体
4 font.setPointSizeF(m_fontSize->value());//设置字体大小
5 m_chart->legend()->setFont(font);
3. 附着图表时设置边框
1 m_chart->legend()->setGeometry(QRectF(x,y,width,height));
2 m_chart->legend()->update();
4. 关联图表说明与图表
实现效果:点击图表说明时,相应的图表被显示或隐藏。
建立信号QLegendMarker::clicked-槽handleMarkerClicked关系
1 const auto markers = m_chart->legend()->markers();
2 for (QLegendMarker *marker : markers) {
3 // Disconnect possible existing connection to avoid multiple connections
4 QObject::disconnect(marker, &QLegendMarker::clicked,
5 this, &MainWidget::handleMarkerClicked);
6 QObject::connect(marker, &QLegendMarker::clicked, this, &MainWidget::handleMarkerClicked);
7 }
槽函数handleMarkerClicked实现
1 void handleMarkerClicked()
2 {
3 //通过关联机制获取当前点击的LegendMarker
4 QLegendMarker* marker = qobject_cast<QLegendMarker*> (sender());
5 Q_ASSERT(marker);//若LegendMarker为空,则退出
6
7 switch (marker->type())
8 {
9 //LegendMarkerType有以下几种情况:
10 //LegendMarkerTypeXY表示line,spline,scatter的LegendMarker
11 //LegendMarkerTypeArea表示area的LegendMarker
12 //LegendMarkerTypeBar表示bar柱状图的LegendMarker
13 //LegendMarkerTypePie表示pie饼状图的LegendMarker
14 //LegendMarkerTypeBoxPlot表示盒形图的LegendMarker
15 //LegendMarkerTypeCandlestick表示蜡烛图的LegendMarker
16 case QLegendMarker::LegendMarkerTypeXY:
17 {
18
19 marker->series()->setVisible(!marker->series()->isVisible());
20
21 // Turn legend marker back to visible, since hiding series also hides the marker
22 // and we don't want it to happen now.
23 marker->setVisible(true);
24
25 // Dim the marker, if series is not visible
26 qreal alpha = 1.0;
27
28 if (!marker->series()->isVisible())
29 alpha = 0.5;
30
31 QColor color;
32 QBrush brush = marker->labelBrush();
33 color = brush.color();
34 color.setAlphaF(alpha);
35 brush.setColor(color);
36 marker->setLabelBrush(brush);
37
38 brush = marker->brush();
39 color = brush.color();
40 color.setAlphaF(alpha);
41 brush.setColor(color);
42 marker->setBrush(brush);
43
44 QPen pen = marker->pen();
45 color = pen.color();
46 color.setAlphaF(alpha);
47 pen.setColor(color);
48 marker->setPen(pen);
49
50 break;
51 }
52 default:
53 {
54 qDebug() << "Unknown marker type";
55 break;
56 }
57 }
58 }