我正在使用 QPrinter 和 QPainter 这些类来使用Windows虚拟设备打印成PDF文件。 QPainter 对象打开一个对话窗口,可以在其中引入PDF文件的路径和名称。
它适用于有意使用。但是,在对话框中按取消按钮时,应用程序崩溃。以下是复制错误的代码段:
#include <iostream>
#include <QApplication>
#include <QPrinterInfo>
#include <QPainter>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
foreach(QPrinterInfo printerInfo, QPrinterInfo::availablePrinters()) {
if (printerInfo.state() == QPrinter::PrinterState::Error)
continue;
// Look for the virtual printer device that generates a pdf.
if (printerInfo.printerName() == "Microsoft Print to PDF")
{
QPrinter * qPrinter = new QPrinter(printerInfo, QPrinter::HighResolution);
QPainter * qPainter = new QPainter();
// This statement pops up a file selection dialog.
// When it is cancelled, the application crashes ...
qPainter->begin(qPrinter);
// ... and this statement is never reached.
std::cout << "Starting printing on the pdf file." << std::endl;
// We print some text in the PDF file.
qPainter->drawText(100, 100, "Lorem ipsum dolor sit amet, consectetur adipiscing elit.");
qPrinter->newPage();
qPainter->drawText(100, 100, "Mauris ut urna eget dui eleifend placerat.");
qPrinter->newPage();
// Close the printer and clean-up.
qPainter->end();
delete qPrinter;
delete qPainter;
}
}
return 0;
}
按取消按钮,应用程序在调用 QPainter :: begin()期间崩溃。我错过了什么吗?该方法可能存在错误吗?
更新:使用try-catch保护对QPainter :: begin()的调用并不能防止崩溃:
#include <iostream>
#include <QApplication>
#include <QPrinterInfo>
#include <QPainter>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
foreach(QPrinterInfo printerInfo, QPrinterInfo::availablePrinters()) {
if (printerInfo.state() == QPrinter::PrinterState::Error)
continue;
// Look for the virtual printer device that generates a pdf.
if (printerInfo.printerName() == "Microsoft Print to PDF")
{
QPrinter * qPrinter = new QPrinter(printerInfo, QPrinter::HighResolution);
QPainter * qPainter = new QPainter();
// This statement pops up a file selection dialog.
// When it is cancelled, the application crashes ...
try
{
qPainter->begin(qPrinter);
}
catch(...) { }
// ... and this statement is never reached.
std::cout << "Starting printing on the pdf file." << std::endl;
if (qPainter->isActive())
{
// We print some text in the PDF file.
qPainter->drawText(100, 100, "Lorem ipsum dolor sit amet, consectetur adipiscing elit.");
qPrinter->newPage();
qPainter->drawText(100, 100, "Mauris ut urna eget dui eleifend placerat.");
qPrinter->newPage();
qPainter->end();
}
// Close the printer and clean-up.
delete qPrinter;
delete qPainter;
}
}
return 0;
}
答案 0 :(得分:0)
尝试使用QPrinter::ScreenResolution
代替QPrinter::HighResolution
。
PDF打印机sets 1200 dpi导致500 MB内存分配,32位Qt太多,然后崩溃就是来自QImage的malloc。
或者你可以切换到64位Qt。它仍然会很慢,但打印很好。如果您想要比ScreenResolution
更高的dpi,则可以将QPrinter::setResolution(int dpi)
设置为300以上。