After experimenting, it seems that the painter
has to clean up before the pixmap
does, otherwise you get the error. For example, this works without error.
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
You can also tell the painter
to clean up without destroying it. Just tell it that you've finished painting by calling 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()
There are some other things that avoid the error for mysterious reasons. For example, this avoids the error.
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.')
In summary, just make sure that the painter cleans up before the pixmap does. I would recommend either using the painter in a smaller scope than the pixmap or explicitly calling painter.end()
.