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).
JavaScript
x
54
54
1
import pyqtgraph as pg
2
from pyqtgraph.graphicsItems.LegendItem import ItemSample
3
from PyQt5 import QtCore, QtGui, QtWidgets
4
5
class LegendItem(pg.LegendItem):
6
7
clicked = QtCore.pyqtSignal(int)
8
9
def __init__(self, *args, **kwargs):
10
super().__init__(*args, **kwargs)
11
self._group = QtWidgets.QButtonGroup()
12
13
def addItem(self, item, name):
14
widget = QtWidgets.QRadioButton(name)
15
palette = widget.palette()
16
palette.setColor(QtGui.QPalette.Window, QtCore.Qt.transparent)
17
palette.setColor(QtGui.QPalette.WindowText, QtCore.Qt.white)
18
widget.setPalette(palette)
19
self._group.addButton(widget)
20
row = self.layout.rowCount()
21
widget.clicked.connect(lambda: self.clicked.emit(row))
22
proxy = item.scene().addWidget(widget)
23
if isinstance(item, ItemSample):
24
sample = item
25
else:
26
sample = ItemSample(item)
27
self.layout.addItem(proxy, row, 0)
28
self.layout.addItem(sample, row, 1)
29
self.items.append((proxy, sample))
30
self.updateSize()
31
32
if __name__ == '__main__':
33
app = QtWidgets.QApplication([])
34
35
plt = pg.PlotWidget()
36
plt.setWindowTitle('Legend with radiobuttons')
37
38
legend = LegendItem(verSpacing=5, horSpacing=5)
39
legend.setParentItem(plt.getViewBox())
40
41
plt.plotItem.legend = legend
42
43
c1 = plt.plot([1,3,2,4], pen='r', symbol='o', symbolPen='r', symbolBrush=0.5, name='red plot')
44
c2 = plt.plot([2,1,4,3], pen='g', fillLevel=0, fillBrush=(255,255,255,30), name='green plot')
45
46
def onClicked(index):
47
print("{} clicked".format(index))
48
49
legend.clicked.connect(onClicked)
50
51
plt.show()
52
53
app.exec()
54