I want to control which curves are displayed at the figure by using the radiobuttons floating on the left-top corner, which will work also as a legend. How can I do that?
Advertisement
Answer
This could be achieved by inheiring pg.LegendItem and overriding addItem method. In it you need to create widgets and place them into layout. You can use QGraphicsProxyWidget to display QRadioButton on QGraphicsScene (PlotWidget).
import pyqtgraph as pg
from pyqtgraph.graphicsItems.LegendItem import ItemSample
from PyQt5 import QtCore, QtGui, QtWidgets
class LegendItem(pg.LegendItem):
clicked = QtCore.pyqtSignal(int)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._group = QtWidgets.QButtonGroup()
def addItem(self, item, name):
widget = QtWidgets.QRadioButton(name)
palette = widget.palette()
palette.setColor(QtGui.QPalette.Window, QtCore.Qt.transparent)
palette.setColor(QtGui.QPalette.WindowText, QtCore.Qt.white)
widget.setPalette(palette)
self._group.addButton(widget)
row = self.layout.rowCount()
widget.clicked.connect(lambda: self.clicked.emit(row))
proxy = item.scene().addWidget(widget)
if isinstance(item, ItemSample):
sample = item
else:
sample = ItemSample(item)
self.layout.addItem(proxy, row, 0)
self.layout.addItem(sample, row, 1)
self.items.append((proxy, sample))
self.updateSize()
if __name__ == '__main__':
app = QtWidgets.QApplication([])
plt = pg.PlotWidget()
plt.setWindowTitle('Legend with radiobuttons')
legend = LegendItem(verSpacing=5, horSpacing=5)
legend.setParentItem(plt.getViewBox())
plt.plotItem.legend = legend
c1 = plt.plot([1,3,2,4], pen='r', symbol='o', symbolPen='r', symbolBrush=0.5, name='red plot')
c2 = plt.plot([2,1,4,3], pen='g', fillLevel=0, fillBrush=(255,255,255,30), name='green plot')
def onClicked(index):
print("{} clicked".format(index))
legend.clicked.connect(onClicked)
plt.show()
app.exec()