QPrinter/QPainter memory leak

228 Views Asked by At

I'm having trouble with memory management while printing in Qt. The following code appears to have a memory leak. After calling QPainter::drawImage the QImage doesn't seem to get cleaned up (or at least it leaves behind 500k or more of memory on the heap). And if I comment out the call to QPainter::drawImage I don't get a memory leak. Can you see what I might be doing wrong here? Can you see where the leak is happening?

bool doPrint()
{
    QPrinter printer;

    // select the printer
    printer.setPaperSize(QPagedPaintDevice::Letter);

    QSharedPointer<QPrintDialog> printDialog(new QPrintDialog(&printer, Q_NULLPTR));
    printDialog->setOption(QAbstractPrintDialog::PrintToFile);
    printDialog->setOption(QAbstractPrintDialog::PrintSelection);
    printDialog->setOption(QAbstractPrintDialog::PrintPageRange);
    printDialog->setOption(QAbstractPrintDialog::PrintCollateCopies);
    printDialog->setOption(QAbstractPrintDialog::PrintCurrentPage);
    printDialog->setFromTo(currentPage_ + 1, currentPage_ + 1);
    if (printDialog->exec() != QDialog::Accepted)
    {
        return false;
    }

    printer.setResolution(300);
    printer.setFullPage(false);

    QPainter painter;
    if (!painter.begin(&printer))
    {
        qWarning() << "Can't start printing...";
        return false;
    }

    for (int i=0; i<5; i++)
    {
        if (i != 0)
        {
            printer.newPage();
        }

        QImage image(300*8.5, 300*11.0, QImage::Format_ARGB32);
        image.fill(qRgba(
                       QRandomGenerator::global()->bounded(255),
                       QRandomGenerator::global()->bounded(255),
                       QRandomGenerator::global()->bounded(255),
                       255)
                   );
        if (!image.isNull())
        {
            painter.drawImage(0, 0, image);
        }
    }

    painter.end();

    return true;
}
0

There are 0 best solutions below