如何绕过pyqtgraph中setData方法的内置清除机制批量绘图?
解决pyqtgraph绘制多个方块网格的问题
核心问题原因
PlotDataItem.setData()的设计逻辑就是更新当前Item的数据,调用它会直接替换掉该Item之前所有的绘图内容,所以循环调用同一个Item的setData只会保留最后一次的数据——这不是什么需要“绕过”的清除机制,是它的正常工作方式。
直接可行的解决方案:为每个方块创建独立的PlotDataItem
不需要纠结现有方法的限制,正确的做法是给字典里的每一组方块数据单独创建一个PlotDataItem,再把这些Item全部添加到同一个画布中。示例代码如下:
import pyqtgraph as pg from PyQt5.QtWidgets import QApplication import sys # 模拟你的方块数据字典 square_data = { 'p0a0': [[1255.19, 1430.18, 1428.17, 1253.18, 1255.19], [407.79, 409.63, 600.62, 598.78, 407.79]], 'p0a1': [[1435.20, 1610.19, 1608.18, 1433.19, 1435.20], [407.79, 409.63, 600.62, 598.78, 407.79]], # 这里省略其他62个方块的数据 } app = QApplication(sys.argv) plot_widget = pg.PlotWidget() plot_widget.show() # 遍历数据,为每个方块生成独立的绘图Item for key, coords in square_data.items(): x_coords, y_coords = coords # 创建新的PlotDataItem,设置数据后添加到画布 plot_item = pg.PlotDataItem(x=x_coords, y=y_coords, pen='b', fillLevel=0, brush='lightblue') plot_widget.addItem(plot_item) sys.exit(app.exec_())
优化方案:用GraphicsPathItem绘制多边形(更适合批量方块)
如果你的方块是闭合多边形,用pg.GraphicsPathItem会更高效,尤其是处理64个方块这种批量场景:
import pyqtgraph as pg from PyQt5.QtGui import QPainterPath from PyQt5.QtWidgets import QApplication import sys square_data = { 'p0a0': [[1255.19, 1430.18, 1428.17, 1253.18, 1255.19], [407.79, 409.63, 600.62, 598.78, 407.79]], 'p0a1': [[1435.20, 1610.19, 1608.18, 1433.19, 1435.20], [407.79, 409.63, 600.62, 598.78, 407.79]], } app = QApplication(sys.argv) plot_widget = pg.PlotWidget() plot_widget.show() for key, coords in square_data.items(): x_coords, y_coords = coords path = QPainterPath() # 按坐标顺序绘制闭合路径 path.moveTo(x_coords[0], y_coords[0]) for x, y in zip(x_coords[1:], y_coords[1:]): path.lineTo(x, y) # 创建路径绘图Item并添加到画布 path_item = pg.GraphicsPathItem(path, pen='b', brush='lightblue') plot_widget.addItem(path_item) sys.exit(app.exec_())
为什么传入整个字典无效?
PlotDataItem.setData()只接受单个曲线/多边形的x、y数组,根本不支持直接传入字典格式的数据,所以这种调用方式本身就不符合API要求。
内容的提问来源于stack exchange,提问作者Gihan
相关产品推荐
相关产品推荐

