我正在使用类QPrinter和QPainter打印成PDF文件与一个Windows虚拟设备。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;
}通过按下Cancel按钮,应用程序在调用QPainter::begin()时崩溃。我是不是遗漏了什么?这种方法可能有错误吗?
更新:保护对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;
}发布于 2018-01-13 15:36:37
尝试使用QPrinter::ScreenResolution而不是QPrinter::HighResolution。
PDF打印机设置1200 dpi导致了500 MB的内存分配,这对于32位Qt来说太多了,因此崩溃的原因是来自QImage的malloc。
或者,您可以切换到64位Qt。它仍然是缓慢的,但打印很好。如果您想要比ScreenResolution更高的dpi,可以使用QPrinter::setResolution(int dpi)将其设置为300左右。
https://stackoverflow.com/questions/38093486
复制相似问题