Qt World Summit: Submit your Presentation

memory leak width QPainter/QPrinter

  • I have a memory leak problem while simply using QPrinter/QPainter in my C++/QT application.

    I need in my program to print several pictures choosen by the user (from 1 to up to 20), but each time the memory used raise up to about 200/500 Mo each time(depend of number of pictures choosen) with my little test project and about 1/2 Go with the main program and high quality pictures and doesnt'n bring back after print task.
    That happen even with normal QPrinter/QPainter variable as shown balow.

    So, is there a mean of QPrinter/QPainter usage to avoid memory leak when use it several time in a row?

    It's for a photobooth desktop software, so that's a problem and cause program crash or very slow after 10 or more pictures and/or print task.

    The problem doesn't appear when I use printer.setOutputFormat(QPrinter::PdfFormat); but I need to print to another printer.

    I ever tried some modifications such as put QPrinter and QPainter variable in member of wind object,try in debug mode with vs, or release without it... but it's the same.

    I use Visual studio 2017 with QT 5.12.2 (msvc2017 64 bits).

    Here a code example to illustrate this problem:

    wind::wind(QWidget *parent) :
    	QWidget(parent) {
    	_printOut = new QPushButton("Print");
    	connect(_printOut, &QPushButton::clicked, this, &wind::printOut);
    	QGridLayout *lay = new QGridLayout();
    	_photoPrinterComboBox = new QComboBox();
    	QStringList printList = QPrinterInfo::availablePrinterNames();
    void wind::printOut()
    	QPrinterInfo printerInfo = QPrinterInfo::printerInfo(_photoPrinterComboBox->currentText());
    	QPrinter printer(printerInfo, QPrinter::HighResolution);
    	QStringList files = QFileDialog::getOpenFileNames(this, "choisir images", "", "*.jpg", 0);
    	QPainter paint;
    	for (int i(0); i < files.size(); i++) {
    		QPixmap img;
    		bool succ = img.load(files.at(i));
    		if (succ) {
    			QFileInfo fi(files.at(i));
    			qreal dpiX = printer.physicalDpiX();
    			qreal dpiY = printer.physicalDpiY();
    			paint.setRenderHint(QPainter::Antialiasing, true);
    			QTransform trMillimeters = QTransform::fromScale(dpiX / 25.400, dpiY / 25.400);
    			paint.setWorldTransform(trMillimeters, false);
    			paint.drawPixmap(img.rect(), img); // the problem seem to appear here

    Thanks in advance for your help,


  • What OS / Qt version are you using?
    Do you see this issue no matter which printer you use?
    Do you see this issue if you paint to a QPixmap instead of a QPrinter (just for testing)?
    Have you researched the Qt issue list https://bugreports.qt.io/issues ?

  • Hi! thank for your reply.

    I use Visual studio 2017 with QT 5.12.2 (msvc2017 64 bits) as a said in my post.
    OS: windows 10 64 bits.
    I ever try with physical and "microsoft print to pdf" printer and it's the same.
    If I paint to a QPixmap created in the stack (destroyed at the end of the block) the issues doesn't appear.

  • @labrass said in memory leak width QPainter/QPrinter:

    for (int i(0); i < files.size(); i++) {

      QPixmap img;

    What if you move QPixmap img outside the loop, before "for"? Truth to tell, I don't see a reason to have it new with every step.

  • @artwaw I just ever do that before your reply but it's the same.

  • @labrass said in memory leak width QPainter/QPrinter:

    and doesnt'n bring back after print task

    I presume you mean you allow the code to return to the Qt main event loop, but do not see a reduction in memory used.

    Can you try: after one run of the 20 images in your code, allow it to return to the Qt event loop as usual. Then re-run with exactly the same 20 images. We want to see whether that uses up new, further memory, or whether that re-uses the memory which was allocated in the first run?

  • @labrass I would suggest you to use QImage instead of QPixmap, I think this will solve your issue.

  • @JonB Yes you're right. So I do that with Qimage instead of QPixmap as suggested @KroMignon but it's the same thinks, the memory go further up after reprinting.

  • @labrass said in memory leak width QPainter/QPrinter:

    but it's the same thinks, the memory go further up after reprinting.

    The only reason I see is that paint.end() does not work, and do not release memory.

    On what kind of printer do you send the image?
    Is the printer accessible/working?

  • @labrass said in memory leak width QPainter/QPrinter:

    Yes you're right.

    In what way? I asked whether memory still increases further if you show the same pictures again, or whether it does not increase any more than it already did?

  • @KroMignon I tried with "microsoft print to pdf printer" and with photo printer (citizen cy printer) plugged by usb, these result are the same, the print task work but still increase memory without down back.

    @JonB I mean, I did as you asked above, and the memory still increases after reprinting the sames pictures second time.

  • I did see memory leak of QPixmap(Qt 5.9.5) before through valgrind on Ubuntu. It was a small issue for me and ignored. But I can not reproduce it from my code now. Make a debug qt build and debug into it to see what is going on if it is a big issue for you.

  • @JoeCFD Ok, unfortunately, I not very at ease for rebuild Qt...
    but I can show the output in debug runtime I notice some strange error, maybe related to this issue (sorry for some french word):

    Exception levée à 0x00007FF88998D759 (KernelBase.dll) dans testPainter.exe : WinRT originate error - 0x80040155 : 'Échec de la recherche de l’inscription de proxy pour IID : {2047E320-F2A9-11CE-AE65-08002B2E1262}.'.
    onecore\com\combase\dcomrem\marshal.cxx(1284)\combase.dll!00007FF88A82DF9B: (caller: 00007FF88A82D354) ReturnHr(7) tid(21cc) 80040155 Interface non enregistrée
        Msg:[Failed to marshal with IID={2047E320-F2A9-11CE-AE65-08002B2E1262}] 
    onecore\com\combase\dcomrem\marshal.cxx(1179)\combase.dll!00007FF88A82D384: (caller: 00007FF88A82973B) LogHr(7) tid(21cc) 80040155 Interface non enregistrée
    onecore\com\combase\dcomrem\marshal.cxx(1119)\combase.dll!00007FF88A9311E0: (caller: 00007FF88A82904D) ReturnHr(8) tid(21cc) 80040155 Interface non enregistrée
    Exception levée à 0x00007FF88998D759 (KernelBase.dll) dans testPainter.exe : 0x80040155: Interface non enregistrée.
    Exception levée à 0x00007FF88998D759 (KernelBase.dll) dans testPainter.exe : 0x80040155: Interface non enregistrée.

  • How do you measure memory usage?
    Which metric do you use?
    Can you repeat until the process crashes because it is out of memory?

    The reason I ask: Depending on which metric you look at, memory may not look to be freed because the OS decides it's not needed, and the process can keep it for the time being. Once other processes request more memory, it should be freed up.
    However, if you can crash your process because it runs out of memory, that would be an indication of a true memory leak.

    It hasn't gotten any easier in the past 20 years to analyze memory leaks...

  • @Asperamanca After several print task in debug mode, I have many "out of memory" error in debug output and my computer even started to have black screen.

    Capture d’écran 2021-04-01 112048.png

  • I can reproduce this on Windows using either an HP LaserJet printer or Microsoft Print to PDF printer. This has been happening in my application for awhile (maybe a year or more) but I always thought it was a leak in my code. After debugging I found that the Qt printing system is most likely at fault, and probably only on Windows. (I build my code for both Mac OS X and Windows and the Mac OS X doesn't leak memory.)

    The following bug report has been filed:


    It contains a couple sample projects that reproduce this memory leak. The project QPainterTest.zip attached to that bug report contains the following leaky code :

    void Widget::showEvent(QShowEvent *)
        QPrinter printer;
        // select the printer
        QSharedPointer<QPrintDialog> printDialog(new QPrintDialog(&printer, Q_NULLPTR));
        if (printDialog->exec() != QDialog::Accepted)
        QPainter painter;
        if (!painter.begin(&printer))
        for (int i=0; i<10; i++)
            if (i != 0)
            QImage image(300*8.5, 300*11, QImage::Format_ARGB32);
            image.fill(qRgb(215, 215, 215));
            painter.drawImage(0, 0, image);

    Any thoughts would be much appreciated.

  • Lifetime Qt Champion

    @AaronC said in memory leak width QPainter/QPrinter:

    Any thoughts would be much appreciated.

    The problem is inside QWin32PrintEngine::drawPixmap() where hbitmap is not released once it is used via SelectObject() for unknown reason. All looks fine according the docs and intensive searching.

  • @Christian-Ehrlicher Thanks for tracking that down. Hope Qt gets it fixed soon.