Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error printing image in PyQt

I'm trying to print a widget in PyQt, but am getting the error that "QPaintDevice: Cannot destroy paint device that is being painted". I think the problem is that my method ends, and therefore the qPaintDevice is destroyed, before the painter has finished drawing the pixmap. I have no idea how to slow the painter down, however.

The code for my method is here:

def printer(self):
    "Prints the current diagram"
    # Create the printer
    printerobject = QtGui.QPrinter(0)
    # Set the settings
    printdialog = QtGui.QPrintDialog(printerobject)
    if printdialog.exec_() == QtGui.QDialog.Accepted:
        # Print
        pixmapImage = QtGui.QPixmap.grabWidget(self.contentswidget)
        painter = QtGui.QPainter(printerobject)
        painter.drawPixmap(0, 0, pixmapImage)

For what it's worth, I tried using the .begin() and .end() approach, to no avail.

like image 409
Wilbur Avatar asked Feb 15 '23 04:02

Wilbur


1 Answers

I figured out my problem -- I was forgetting to delete the painter, which in hindsight seems obvious (doesn't it always?). Adding "del painter" to the end makes the code work. Here is working code:

def printer(self):
    "Prints the current diagram"
    # Create the printer
    printerobject = QtGui.QPrinter(0)
    # Set the settings
    printdialog = QtGui.QPrintDialog(printerobject)
    if printdialog.exec_() == QtGui.QDialog.Accepted:
        # Print
        pixmapImage = QtGui.QPixmap.grabWidget(self.contentswidget)
        painter = QtGui.QPainter(printerobject)
        painter.drawPixmap(0, 0, pixmapImage)
        del painter
like image 97
Wilbur Avatar answered Feb 24 '23 09:02

Wilbur