我正在尝试在QPixmap
上绘制一些内容,但是在清理过程中会引发错误。
from PySide2.QtGui import QPixmap, QPainter
from PySide2.QtWidgets import QApplication
app = QApplication()
width = 200
height = 100
pixmap = QPixmap(width, height)
painter = QPainter(pixmap)
painter.drawLine(0, 0, 100, 100)
print('Done.')
[运行时,我看到“完成”消息,然后出现错误。
Done.
QPaintDevice: Cannot destroy paint device that is being painted
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
我见过一些类似的问题,但有相同的错误,但不清楚是什么原因导致了该错误或如何避免该错误。
[经过实验后,看来painter
必须先清理pixmap
,否则会收到错误消息。例如,这可以正常工作。
from PySide2.QtGui import QPixmap, QPainter
from PySide2.QtWidgets import QApplication
app = QApplication()
width = 200
height = 100
pixmap = QPixmap(width, height)
painter = QPainter(pixmap)
painter.drawLine(0, 0, 100, 100)
print('Done.')
del painter
del pixmap
您还可以告诉painter
清理而不破坏它。只需通过调用end()
来告知您已完成绘画。
from PySide2.QtGui import QPixmap, QPainter
from PySide2.QtWidgets import QApplication
app = QApplication()
width = 200
height = 100
pixmap = QPixmap(width, height)
painter = QPainter(pixmap)
painter.drawLine(0, 0, 100, 100)
print('Done.')
painter.end()
出于神秘原因,还有其他一些避免错误的方法。例如,这避免了错误。
from PySide2.QtGui import QPixmap, QPainter
from PySide2.QtWidgets import QApplication
app = QApplication()
width = 200
height = 100
pixmap = QPixmap(width, height)
painter = QPainter(pixmap)
painter.device() # <-- No idea why this helps!
painter.drawLine(0, 0, 100, 100)
print('Done.')
总之,请确保在像素图之前清理画家。我建议要么在比像素图小的范围内使用painter,要么显式调用painter.end()
。