我有一个QGraphicsScene和许多QGraphicsItem。某些项目具有清除和重新绘制场景的按钮。
问题是clear()方法在使用那些非常数据结构的方法调用中删除QButton(及其关联的数据结构)。然后,在clear()返回后,调用方法立即尝试访问现在删除的数据(因为它不期望在其例程中删除),然后发生崩溃。来自here。
我找到了C ++ here的解决方案,但我使用PySide并且无法使用相同的python解决方案。
关注我的代码:
class GraphicsComponentButtonItem(QtGui.QGraphicsItem):
def __init__(self, x, y, update_out):
super(GraphicsComponentButtonItem, self).__init__()
self.x = x
self.y = y
self.update_out = update_out
self.setPos(x, y)
self.createButton()
self.proxy = QtGui.QGraphicsProxyWidget(self)
self.proxy.setWidget(self.button)
def boundingRect(self):
return QtCore.QRectF(self.x, self.y, self.button.width(), self.button.height())
def paint(self, painter, option, widget):
# Paint same stuffs
def createButton(self):
self.button = QtGui.QPushButton()
self.button.setText('Clear')
self.button.clicked.connect(self.action_press)
def action_press(self):
# Run some things
self.update_out()
class QGraphicsViewButtons(QtGui.QGraphicsView):
def __init__(self, scene, parent=None):
QtGui.QGraphicsView.__init__(self, parent)
self.scene = scene
# It's called outside
def updateScene(self):
self.scene.clear()
self.scene.addItem(GraphicsComponentButtonItem(0, 0, self.updateScene))
self.scene.addItem(GraphicsComponentButtonItem(0, 50, self.updateScene))
self.scene.addItem(GraphicsComponentButtonItem(0, 100, self.updateScene))
转换以下C ++代码:
QObject::connect(button, SIGNAL(clicked()), scene, SLOT(clear()), Qt::QueuedConnection);
到python是:
self.button.clicked.connect(self.scene().clear, QtCore.Qt.QueuedConnection)