c – 如何在Qt中打印QWidget?

我需要知道如何将QWidget打印为PDF文件. Widget(QDialog)包含许多标签,一些QPlainTextEdit和一个背景图像.对话框显示已收到所有字段的收据.

我已经尝试过为此目的使用QTextDocument和html,但收据的复杂性(大量图像和格式自定义)使得html输出完全搞砸了.

这是文件.

收据图片

解决方法:

您必须使用QPrinter,这是您必须使用的对象,并且需要QPainter在QPrinter中绘制窗口小部件.

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();
}

小工具:

c  – 如何在Qt中打印QWidget?

输出.pdf

c  – 如何在Qt中打印QWidget?

上一篇:3-Qt5自带mingw7.3.0 64bit 编译GSL科学计算库


下一篇:qt5-工程文件的介绍