我尝试在单独的页面中呈现qwidgets并将其保存为pdf格式。我尝试使用Qpainter,Qprinter并尝试按照论坛中的建议进行渲染:http://doc.qt.io/qt-4.8/printing.html#printing-widgets
这是我的示例代码:
QPainter painter;
painter.begin(&printer);
for(int page = 0;page<no_of_pages;page++)
{
double xscale = printer.pageRect().width()/double(MyWidget[page]->width());
double yscale = printer.pageRect().height()/double(MyWidget[page]->height());
double scale = qMin(xscale, yscale);
painter.translate(printer.paperRect().x() + printer.pageRect().width()/2,
printer.paperRect().y() + printer.pageRect().height()/2);
painter.scale(scale, scale);
painter.translate(-MyWidget[page]->width()/2, -MyWidget[page]->height()/2);
MyWidget[page]->render(&painter);
if(page!=(no_of_pages-1))
printer.newPage();
}
painter.end();
当我执行上面的代码时,生成的pdf中包含确切的页数,但只打印了第一页。当我检查应用程序输出控制台时,将打印以下消息:
QPainter::begin: Paint device returned engine == 0, type: 2
QPainter::setRenderHint: Painter must be active to set rendering hints
QPainter::setWorldTransform: Painter not active
QWidget::render: Cannot render with an inactive painter
QPainter::end: Painter not active, aborted
我试图谷歌关于这些消息,但没有一个与渲染qwidgets相关。任何帮助表示赞赏。谢谢。
答案 0 :(得分:1)
问题不在于它不会在下一页上打印,但是比例不正确,您必须在每次迭代结束时使用resetTransform()
重置所有转换。我更喜欢将小部件保存在QList <QWidget *>
。
QList <QWidget *> widgets;
widgets.append({some widget});
[...]
QPrinter printer;
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName("printer.pdf");
QPainter painter;
if (! painter.begin(&printer)) { // failed to open file
qWarning("failed to open file, is it writable?");
}
for(auto widget: w){
if(widget){
if(widget->width() > 0 && widget->height() >0 ){
qreal xscale = 0.9*printer.pageRect().width()/qreal(widget->width());
qreal yscale = 0.9*printer.pageRect().height()/qreal(widget->height());
qreal scale = qMin(xscale, yscale);
painter.translate(printer.paperRect().x() + printer.pageRect().width()/2,
printer.paperRect().y() + printer.pageRect().height()/2);
painter.scale(scale, scale);
painter.translate(-width()/2, -height()/2);
widget->render(&painter);
painter.resetTransform();
if(widget != widgets.last())
printer.newPage();
}
}
}
painter.end();
观察:设置因子为0.9,以便以更愉快的方式显示图像。