第二次运行 pyqtgraph 时发生 RuntimeError
Posted
技术标签:
【中文标题】第二次运行 pyqtgraph 时发生 RuntimeError【英文标题】:RuntimeError happens when running pyqtgraph second time 【发布时间】:2021-07-02 19:23:45 【问题描述】:我定义了一个函数来使用 pyqtgraph 对数据进行切片。关闭主窗口并再次运行该函数时,我遇到了 RuntimeError:wrapped C/C++ object of type ViewBox has been deleted
。我的功能如下:
import numpy as np
from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph as pg
def dp_select(dp):
app = pg.mkQApp("NBED selection")
## Create window with two ImageView widgets
win = QtGui.QMainWindow()
win.resize(800, 300)
# win.setWindowTitle('pyqtgraph example: DataSlicing')
cw = QtGui.QWidget()
win.setCentralWidget(cw)
l = QtGui.QGridLayout()
cw.setLayout(l)
imv1 = pg.ImageView()
imv2 = pg.ImageView()
l.addWidget(imv1, 0, 0)
l.addWidget(imv2, 0, 1)
win.show()
roi = pg.RectROI(pos=[5, 5], size=[10, 10], pen='r')
# roi = pg.LineSegmentROI([[10, 64], [120,64]], pen='r')
imv1.addItem(roi)
def update():
nonlocal dp, imv1, imv2
d2 = roi.getArrayRegion(dp, imv1.imageItem, axis=(0, 1))
imv2.setImage(d2)
roi.sigRegionChanged.connect(update)
## Display the data
imv1.setImage(dp)
pg.mkQApp().exec_()
app.closeAllWindows()
y0, x0 = [int(i) for i in roi.pos()]
dy, dx = [int(i) for i in roi.size()]
y1 = y0 + dy
x1 = x0 + dx
return dp[y0:y1, x0:x1]
我在 Jupyter 实验室中运行以下命令:
data = np.random.rand(50, 50)
dp = dp_select(data)
谁能告诉我如何解决这个问题?
【问题讨论】:
【参考方案1】:问题是,当使用非本地时,您正在创建一个额外的范围,因此关闭窗口时处理某些项目的 python 对象不会被破坏,因为它们被认为是全局变量,因此在下一次执行中使用它们,但 C++ 对象不再存在导致该错误。一种可能的解决方案是在不使用非本地(例如使用类)的情况下实现逻辑。
import numpy as np
from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph as pg
class MainWindow(QtGui.QMainWindow):
def __init__(self, dp, parent=None):
super().__init__(parent)
self.dp = dp
self.resize(800, 300)
cw = QtGui.QWidget()
self.setCentralWidget(cw)
l = QtGui.QGridLayout(cw)
self.imv1 = pg.ImageView()
self.imv2 = pg.ImageView()
l.addWidget(self.imv1, 0, 0)
l.addWidget(self.imv2, 0, 1)
self.roi = pg.RectROI(pos=[5, 5], size=[10, 10], pen="r")
self.imv1.addItem(self.roi)
self.roi.sigRegionChanged.connect(self.handle_regionChanged)
self.imv1.setImage(self.dp)
def handle_regionChanged(self):
d2 = self.roi.getArrayRegion(self.dp, self.imv1.imageItem, axis=(0, 1))
self.imv2.setImage(d2)
def dp_select(dp):
app = pg.mkQApp("NBED selection")
## Create window with two ImageView widgets
win = MainWindow(dp)
win.show()
pg.mkQApp().exec_()
app.closeAllWindows()
roi = win.roi
y0, x0 = [int(i) for i in roi.pos()]
dy, dx = [int(i) for i in roi.size()]
y1 = y0 + dy
x1 = x0 + dx
return dp[y0:y1, x0:x1]
【讨论】:
以上是关于第二次运行 pyqtgraph 时发生 RuntimeError的主要内容,如果未能解决你的问题,请参考以下文章
Facebook Marketing Api - 循环运行抛出“AuthorizationException 发生未知错误”。 (第二次)