This application generates a test pdf file using QPrinter and QPainter. The call to QPainter::begin() opens a dialog used to enter the PDF file name and location:

Qt Code:
  1. #include <iostream>
  2. #include <QApplication>
  3. #include <QPrinterInfo>
  4. #include <QPainter>
  5.  
  6. int main(int argc, char *argv[])
  7. {
  8. QApplication app(argc, argv);
  9.  
  10. foreach(QPrinterInfo printerInfo, QPrinterInfo::availablePrinters()) {
  11. if (printerInfo.state() == QPrinter::PrinterState::Error)
  12. continue;
  13.  
  14. // Look for the virtual printer device that generates a pdf.
  15. if (printerInfo.printerName() == "Microsoft Print to PDF")
  16. {
  17. QPrinter * qPrinter = new QPrinter(printerInfo, QPrinter::HighResolution);
  18. QPainter * qPainter = new QPainter();
  19.  
  20. // This statement pops up a file selection dialog.
  21. // When it is cancelled, the application crashes ...
  22. qPainter->begin(qPrinter);
  23.  
  24. // ... and this statement is never reached.
  25. std::cout << "Starting printing on the pdf file." << std::endl;
  26.  
  27. // We print some text in the PDF file.
  28. qPainter->drawText(100, 100, "Lorem ipsum dolor sit amet, consectetur adipiscing elit.");
  29. qPrinter->newPage();
  30. qPainter->drawText(100, 100, "Mauris ut urna eget dui eleifend placerat.");
  31. qPrinter->newPage();
  32.  
  33. // Close the printer and clean-up.
  34. qPainter->end();
  35. delete qPrinter;
  36. delete qPainter;
  37. }
  38. }
  39.  
  40. return 0;
  41. }
To copy to clipboard, switch view to plain text mode 

It works correctly when a PDF file name is introduced in the dialog. However, by clicking on the Cancel button the application crashes during the call to QPainter::begin().

Is there a way to prevent this crash? Is the previous code correct, or is there something missing?

Thanks in advance and best regards.