[英]How to toggle a QCustomPlot graph's visibility by clicking on the legend
我有一个带有多个图形项的 QCustomPlot。
我希望通过单击图例中的相关项目来切换它们的可见性。
QObject::connect(
plot,
&QCustomPlot::legendClick,
[](QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event)
{
// how to get to the relevant graph from the item variable?
}
);
谢谢你。
我建议你试试这个
QObject::connect(
plot,
&QCustomPlot::legendClick,
[](QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event)
{
for (int i=0; i<customPlot->graphCount(); ++i)
{
QCPGraph *graph = customPlot->graph(i);
QCPPlottableLegendItem *itemLegend = customPlot->legend->itemWithPlottable(graph);
QCPPlottableLegendItem *plItem = qobject_cast<QCPPlottableLegendItem*>(item);
if (itemLegend == plItem )
{
//graph the one you need
}
}
};
图形的关联图例项是QCPPlottableLegendItem
。 因此,如果将抽象图例项转换为该项目,则可以直接检索可绘制表(图形)。 因此,您不需要像其他答案那样迭代所有图表:
QCPAbstractLegendItem *yourItem; // the one you get from the event
if (auto plItem = qobject_cast<QCPPlottableLegendItem*>(yourItem))
{
plItem->plottable()->setVisible(!plItem->plottable()->visible())
customPlot->replot(); // don't forget to replot
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.