删除一行后"RuntimeError: wrapped C/C++ object of type PlotCurveItem has been deleted"弹出



我想绘制存储在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)

相关内容

最新更新