为什么当我尝试访问qgraphics项目的parentItem时会导致程序意外崩溃?我试图为这个问题做一个超级简单的例子,它肯定是可以重现的。我在网上找到的唯一与此崩溃有关的文章是:https://www.qtcentre.org/threads/63345-Occasional-crash-related-to-QGraphicsItem-parentItem,它谈论了我已添加但未解决问题的 prepareGeometryChange()。
要重新创建崩溃,只需取消注释此行代码print self.parentItem()
import os, sys, uuid
from Qt import QtWidgets, QtGui, QtCore
class KnotNodeItem(QtWidgets.QGraphicsEllipseItem):
def __init__(self, parent=None):
super(KnotNodeItem, self).__init__(parent=parent)
self.setAcceptHoverEvents(True)
self.setFlags(self.ItemSendsScenePositionChanges | self.ItemIsSelectable | self.ItemIsMovable)
self.setCursor(QtCore.Qt.PointingHandCursor)
# call initial update to draw text with correct visuals from base class
self.update()
# Overrides
def boundingRect(self):
rect = self.rect()
rect.adjust(-1,-1,1,1)
return rect
def itemChange(self, change, value):
if change == self.ItemScenePositionHasChanged:
pass
# print self.parentItem()
return super(KnotNodeItem, self).itemChange(change, value)
def update(self):
self.prepareGeometryChange()
self.setRect(-12, -12, 12*2, 12*2)
super(KnotNodeItem, self).update()
def paint(self, painter, option, widget=None):
painter.save()
painter.setRenderHint(QtGui.QPainter.Antialiasing)
if self.isSelected():
painter.setPen(QtGui.QPen(QtGui.QColor(255,255,255), 4, QtCore.Qt.SolidLine))
else:
painter.setPen(QtGui.QPen(QtGui.QColor(30,30,30), 4, QtCore.Qt.SolidLine))
painter.setBrush(QtGui.QColor(128,128,255))
painter.drawEllipse(self.rect())
painter.restore()
class MainWindowUi(QtWidgets.QMainWindow):
def __init__(self, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs)
self.resize(400,400)
self.scene = QtWidgets.QGraphicsScene(self)
self.scene.setBackgroundBrush(QtGui.QBrush(QtGui.QColor(45,45,45), QtCore.Qt.SolidPattern));
self.view = QtWidgets.QGraphicsView(self)
self.setCentralWidget(self.view)
self.view.setScene(self.scene)
# Create various KnotNodeItems
item = KnotNodeItem()
item.setPos(300,20)
self.scene.addItem(item)
if __name__ == '__main__':
a = QtWidgets.QApplication(sys.argv)
m = MainWindowUi()
m.show()
sys.exit(a.exec_())