【问题标题】:After removing a line "RuntimeError: wrapped C/C++ object of type PlotCurveItem has been deleted" pops up删除一行“RuntimeError:PlotCurveItem 类型的已包装 C/C++ 对象已被删除”后弹出
【发布时间】:2021-06-02 09:53:20
【问题描述】:

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

【问题讨论】:

    标签: python pyqt garbage-collection pyqt5 pyqtgraph


    【解决方案1】:

    问题在于同步,因为似乎在删除后的瞬间,另一个使用已删除项目的代码被执行,因此它会启动该警告。解决办法是用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)
    

    【讨论】:

    • 谢谢,工作正常。也许你也知道如何使它更容易点击线条而不会使线条变粗?
    • @VitaminC 使用curve.curve.setClickable(True, width=20)
    猜你喜欢
    • 1970-01-01
    • 2021-10-03
    • 2020-11-10
    • 2013-07-28
    • 2020-06-01
    • 2019-06-05
    • 1970-01-01
    • 2020-08-29
    • 1970-01-01
    相关资源
    最近更新 更多