PyQwt - Toggling Legend Visibility
Greetings,
I am hoping someone can help with this simple problem. I am trying to toggle the visibility of the legend of a plot but nothing seems to work.
I have tried the following but nothing happens. The legend just remains visible:
Code:
plot.legend().setVisible(False)/plot.legend().setVisible(True)
plot.legend().hide()/plot.legend().show()
I have tried:
Code:
plot.legend().contentsWidget().setVisible(False)/plot.legend().contentsWidget().setVisible(True)
but this just hides the clickable legend items, the box of the legend is still visible which is not what I want. I would like the entire legend to appear or disappear.
I have also tried keeping the legend around in my class after I create it by going:
Code:
#insert legend into plot here
Then, to make the legend “not visible†I remove it by calling
Code:
plot.insertLegend(None)
but then when I try to reinsert my legend to make it “visible†again:
Code:
plot.insertLegend(self.plotLegend, locationNotImportant)
I get an error stating the underlying C++ object has been deleted.
Is there seriously no way to do this without creating a new legend every time? This would seem to be so simple…
Any help is appreciated, thank you.
(Using PyQwt 5.1.0)
Re: PyQwt - Toggling Legend Visibility
In case anyone is actually interested (and because I myself hate seeing questions with no answer or follow-up), I figured out a hack to do this. When the user wishes to hide the legend, I change the position of the legend to External:
Code:
plot.
plotLayout().
setLegendPosition(QwtPlot.
ExternalLegend)plot.legend().setVisible(False)
plot.updateLayout()
The call to setVisible() now successfully hides the legend. Then when the user wishes it to reappear, I change the position back to where it was before (in my case, the right side):
Code:
plot.
plotLayout().
setLegendPosition(QwtPlot.
RightLegend)plot.legend().setVisible(True)
plot.updateLayout()
The legend then reappears thereby retaining the “pressed status†of its items. I came to this solution by going through the Qwt source and noticed something in the updateLayout() method of QwtPlot (and somewhere else as well, though the location eludes me at the moment):
Code:
00454 if ( d_data->legend &&
00455 d_data->layout->legendPosition() != ExternalLegend )
00456 {
00457 if (d_data->legend->itemCount() > 0)
00458 {
00459 d_data->legend->setGeometry(d_data->layout->legendRect());
00460 d_data->legend->show();
00461 }
00462 else
00463 d_data->legend->hide();
00464 }
This code results in the legend always being shown as long as there are items in it no matter what. So no matter how much you try to hide the legend, this will override it and make the legend appear whenever the layout of the plot gets updated. I then noticed that it doesn’t do this when the legend is set as External, which led me to my above solution.
I hope this helps others.