python - 从其中一项的事件中清除 QGraphicsScene

标签 python pyside

我有一个带有许多 QGraphicsItem 的 QGraphicsScene。有些项目具有清除和重新绘制场景的按钮。

The problem is that the clear() method deletes the QButton (and its associated data structures) in the middle of a method call that uses those very data structures. Then, immediately after clear() returns, the calling method tries to access the now-deleted data (because it wasn't expecting to be deleted in the middle of its routine), and bang -- a crash. From 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)

关于python - 从其中一项的事件中清除 QGraphicsScene,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48387136/

相关文章:

python - 导入任意 python 源文件。 (Python 3.3+)

python - ftplib.error_perm : 500 not understood downloading file from ftp

python - 如何每次运行时只抓取更新的部分

python - 从 mac 地址转换为十六进制字符串,反之亦然 - python 2 和 3

python - 在两个不同形状的 DataFrame 中查找相同的数据

python - Pyside:多个 QProcess 输出到 TextEdit

qt - QNetworkAccessManager 和 HTTP 持久连接

Python/PySide : How can i destroy a terminated thread object?

python - 按下按钮时 Pyside 从 QLineEdit 打印文本

image - 是否可以放置图像而不是按钮,并使其可点击?