Uploaded image for project: 'Qt'
  1. Qt
  2. QTBUG-21576

QPrinter::paperSize(QPrinter::Unit) causes crash on Mac after painter goes out of scope

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Won't Do
    • Icon: P3: Somewhat important P3: Somewhat important
    • 4.8.x
    • 4.7.4
    • GUI: Printing
    • None
    • Mac OS X 10.6.8
    • macOS

      Here is a piece of code that usually reproduces the problem. (There appears to be some kind of race condition ... sometimes this works without crashing. At least on my machine, however, it usually fails.)

      main.cpp
      #include <QtGui>
      
      int main(int argc, char **argv) {
        QApplication app(argc, argv);
      
        QMainWindow w;
        w.show();
      
        QPrinter printer(QPrinter::HighResolution);
        qDebug() << printer.paperSize(QPrinter::Inch);
      
        QPrintDialog dialog(&printer, &w);
        if (QDialog::Accepted == dialog.exec()) {
          QPainter painter(&printer);
          painter.fillRect(0, 0, 500, 500, Qt::BDiagPattern);
        }
      
        qDebug() << printer.paperSize(QPrinter::Inch);  // Crash!
      
        return app.exec();
      }
      

      The first call to QPrinter::paperSize() works, but the second call fails. You must accept the print dialog (eg. by clicking "preview" on the dialog) to get the failure.

      My Objective-C is pretty weak, but it looks like QMacPrintEnginePrivate.format is set to point to an internal handle of QMacPrintEnginePrivate.printInfo in line 463. This initialization occurs in the constructor and whenever a paint operation starts on the print engine. But when the paint operation stop, the printInfo is released (line 494), leaving the format pointer pointing to never-never land. When QMacPrintEnginePrivate::paperSize() attempts to use format, you get the crash.

      You can workaround it by putting a QPainter that operates on the QPrinter in the same scope as your call:

      {
        QPainter temp(&printer);
        qDebug() << printer.paperSize(QPrinter::Inch);  // No crash
      }
      

        For Gerrit Dashboard: QTBUG-21576
        # Subject Branch Project Status CR V

            andysh Andy Shaw
            dmateer Dave Mateer
            Votes:
            4 Vote for this issue
            Watchers:
            10 Start watching this issue

              Created:
              Updated:
              Resolved:

                There are no open Gerrit changes