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.
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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With