使用图例标记
注: 这是 "带 Widgets 图库的图表"示例的一部分。
在本示例中,我们将创建一个应用程序,使用QLegendMarker 点击信号来显示/隐藏图表中的相应系列。连接标记按钮将图例中所有标记的点击信号连接到 handleMarkerClicked 槽。
我们的应用程序中有用于在图表中添加或删除系列的按钮,以及用于连接或断开图例标记点击信号到我们的处理程序的按钮。在上图中,我们连接了标记并点击了其中一个。
// Connect all markers to handler const auto markers = m_chart->legend()->markers(); for (QLegendMarker *marker : markers) { // Disconnect possible existing connection to avoid multiple connections QObject::disconnect(marker, &QLegendMarker::clicked, this, &LegendMarkersWidget::handleMarkerClicked); QObject::connect(marker, &QLegendMarker::clicked, this, &LegendMarkersWidget::handleMarkerClicked); }
在这里,我们将图例中的标记连接到我们的处理程序。为了避免重复连接同一个标记,我们首先要断开它的连接。
const auto markers = m_chart->legend()->markers(); for (QLegendMarker *marker : markers) { QObject::disconnect(marker, &QLegendMarker::clicked, this, &LegendMarkersWidget::handleMarkerClicked); }
在这里,我们断开了所有标记与处理程序的连接。
auto marker = qobject_cast<QLegendMarker *>(sender()); Q_ASSERT(marker);
在处理程序中,我们首先将事件的发送者转换为QLegendMarker 。
switch (marker->type())
然后检查标记的类型。如果我们想访问标记的详细方法并将其转换为正确的类型,就需要这样做。如果我们只需要指向QAbstractSeries 的指针,则无需进行类型转换。如果是饼或条形图系列,我们可能需要指向相关QPieSlice 或QBarSet 的指针。
// Toggle visibility of series marker->series()->setVisible(!marker->series()->isVisible()); // Turn legend marker back to visible, since hiding series also hides the marker // and we don't want it to happen now. marker->setVisible(true);
我们希望在点击标记时切换系列的可见性。为此,我们需要从标记中获取指向相关系列的指针,并切换其可见性。由于图例标记默认跟随系列的可见性,因此我们也要将标记设置为可见。如果不这样做,标记将在图例中不可见,我们就无法再点击它。
// Dim the marker, if series is not visible 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);
与其在系列隐藏时使标记不可见,我们不如调暗标记的颜色。在这里,我们通过修改 LaberBrush 的颜色来实现。
© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.