pyqtgraph:如何在图形图例上添加单选按钮?
Posted
技术标签:
【中文标题】pyqtgraph:如何在图形图例上添加单选按钮?【英文标题】:pyqtgraph: How to add radiobuttons on a figure legend? 【发布时间】:2021-08-01 21:03:46 【问题描述】:我想通过使用浮动在左上角的单选按钮来控制在图中显示哪些曲线,这也可以用作图例。我该怎么做?
【问题讨论】:
【参考方案1】:这可以通过继承pg.LegendItem
并覆盖addItem
方法来实现。您需要在其中创建小部件并将它们放入布局中。您可以使用QGraphicsProxyWidget
在QGraphicsScene
(PlotWidget) 上显示QRadioButton
。
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()
【讨论】:
以上是关于pyqtgraph:如何在图形图例上添加单选按钮?的主要内容,如果未能解决你的问题,请参考以下文章
pyqtgraph:在缩放时保持 TextItem 的恒定位置
winform dataGridView中如何添加单选按钮列?