int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QDialog w;
w.setLayout(new QVBoxLayout());
w.layout()->addWidget(new QLineEdit("text"));
w.layout()->addWidget(new QPushButton("btn"));
w.layout()->addWidget(new QPlainTextEdit("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris rutrum magna semper nisi faucibus, at auctor dolor ullamcorper. Phasellus facilisis blandit augue sit amet placerat. Aliquam nec imperdiet diam. Proin dignissim vulputate metus, nec tincidunt magna vulputate ac. Praesent vel felis ac dolor viverra tempus eu vitae neque. Nulla efficitur gravida arcu id suscipit. Maecenas placerat egestas velit quis interdum. Nulla diam massa, hendrerit vitae mi et, placerat aliquam nisl. Donec tincidunt lobortis orci, quis egestas augue tempus sed. Nulla vel dolor eget ipsum accumsan placerat ut at magna."));
w.show();
QPushButton btn("print");
btn.show();
QObject::connect(&btn, &QPushButton::clicked, [&w](){
QPrinter printer(QPrinter::HighResolution);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName("output.pdf");
printer.setPageMargins(12, 16, 12, 20, QPrinter::Millimeter);
printer.setFullPage(false);
QPainter painter(&printer);
double xscale = printer.pageRect().width() / double(w.width());
double yscale = printer.pageRect().height() / double(w.height());
double scale = qMin(xscale, yscale);
painter.translate(printer.paperRect().center());
painter.scale(scale, scale);
painter.translate(-w.width()/ 2, -w.height()/ 2);
w.render(&painter);
});
return a.exec();
}
2条答案
按热度按时间wi3ka0sx1#
你必须使用
QPrinter
,这是你必须使用的对象,需要QPainter
在QPrinter
中绘制小部件。小部件:
output.pdf
yshpjwxd2#
Eyllanesc的解决方案工作得很好,但我在
pageRect()
和paperRect()
函数上有警告。这个功能似乎已经过时了。下面是不包含弃用函数的before和after代码。我在
sizePixels()
函数中使用了96,因为它是默认分辨率。希望这段代码能帮上忙:)