After removing a line "RuntimeError: wrapped C/C++ object of type PlotCurveItem has been deleted" pops up

After removing a line "RuntimeError: wrapped C/C++ object of type PlotCurveItem has been deleted" pops up

我想绘制存储在 numpy 数组列表中的一些数据,并能够单击绘制的线条。 单击一行后,需要从我的数据中删除该行,并清除并重绘其他所有内容。

只是从绘图中删除线条 pw.getPlotItem().removeItem(curve) 不是一种选择,有时我需要清除所有内容。

所以问题是如何避免烦人的 RuntimeError: wrapped C/C++ object of type PlotCurveItem has been deleted 错误?这是我所说的最小示例。

# -*- coding: utf-8 -*-
from pyqtgraph.Qt import QtGui
import numpy as np
import pyqtgraph as pg

app = pg.mkQApp()
mw = QtGui.QMainWindow()
mw.resize(800, 800)
cw = QtGui.QWidget()
mw.setCentralWidget(cw)
l = QtGui.QVBoxLayout()
cw.setLayout(l)

pw = pg.PlotWidget()
l.addWidget(pw)
mw.show()

lines = [np.random.normal(size=5) for _ in range(5)]
curves_list = []


def clicked(curve):
    idx = pw.getPlotItem().items.index(curve)
    del lines[idx]
    draw()

    # this is not an option
    # pw.getPlotItem().removeItem(curve)


def draw():
    pw.clear()
    curves_list.clear()
    for line in lines:
        curve = pw.plot(line)
        curve.curve.setClickable(True)
        curve.sigClicked.connect(clicked)
        curves_list.append(curve)


draw()

if __name__ == '__main__':
    QtGui.QApplication.instance().exec_()

问题是同步问题,因为似乎在删除后立即执行另一个使用已删除项目的代码,因此它会发出该警告。解决方案是用 QTimer.singleShot(0, ...):

给它一点延迟
from pyqtgraph.Qt import QtCore, QtGui
def clicked(curve):
    def on_timeout():
        curves_list.remove(curve)
        pw.removeItem(curve)
        draw()

    QtCore.QTimer.singleShot(0, on_timeout)