PySide2引发错误,“ QPaintDevice:无法销毁正在绘制的绘制设备” [重复]

问题描述 投票:0回答:1

我正在尝试在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)

我见过一些类似的问题,但有相同的错误,但不清楚是什么原因导致了该错误或如何避免该错误。

python pyside2
1个回答
0
投票

[经过实验后,看来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()

© www.soinside.com 2019 - 2024. All rights reserved.