简体   繁体   English

打印不适用于QPrinter和QPainter

[英]Printing not working with QPrinter and a QPainter

I want to print some message via my printer, but nothing happens when I compile. 我想通过打印机打印一些消息,但是编译时没有任何反应。 What is the problem with my code? 我的代码有什么问题?

QPrinter printer(QPrinter::HighResolution);
printer.setCreator("Me");
printer.setDocName("Test1");

QPrintDialog *PrintConfiguration = new QPrintDialog(&printer,this);
PrintConfiguration->show();

QPainter *painter = new QPainter(&printer);
painter.drawText(10,10,ui->textEdit->toPlainText());

The code, as presented, won't do anything since you never destruct the painter nor finish the page. 如前所述,该代码不会执行任何操作,因为您永远不会破坏画家或完成页面。 You need to destruct the painter: delete painter; 您需要破坏画家: delete painter; . Alternatively, if you print multiple pages, you need to call printer.newPage() every time you're done with a page. 另外,如果要打印多页,则每次处理printer.newPage()一页后都需要调用printer.newPage()

The drawText may very likely draw in a non-printable area of the page. drawText很可能会在页面的不可打印区域中绘制。 Try: 尝试:

painter->drawText(printer.pageRect(), ui->textEdit->toPlainText());

Problem is here: PrintConfiguration->show(); 问题在这里: PrintConfiguration->show();
show() preparers widget to be show and immediately returns. show()准备show()小部件并立即返回。 So result is that you are trying to paint before user managed to do any interaction with UI and you printer object is not set properly. 因此,结果是您试图在用户设法与UI进行任何交互之前绘画,并且您的打印机对象设置不正确。 You wanted a blocking method: exec() . 您需要一个阻塞方法: exec() Proper code should look like this: 正确的代码应如下所示:

QPrinter printer(QPrinter::HighResolution);
printer.setCreator("Me");
printer.setDocName("Test1");

QPrintDialog printDialog(printer, this);
if (printDialog.exec() == QDialog::Accepted) {
    QPainter painter(&printer);
    painter.drawText(10,10,ui->textEdit->toPlainText());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM