QPrintPreviewDialog incorrect preview

2019-06-02 11:08发布

问题:

Using QPrintPreviewDialog to preview the print, I use the following code

    QPrinter printer;
    printer.setResolution(QPrinter::HighResolution);
    printer.setPaperSize(QPrinter::A4);
    printer.setOrientation(QPrinter::Portrait);
    QPrintPreviewDialog *pd = new QPrintPreviewDialog(&printer);
    connect(pd,SIGNAL(paintRequested(QPrinter*)),this,SLOT(print(QPrinter*)));
    pd->exec();


void Class::print(QPrinter *p)
{
    QTextEdit *ted = new QTextEdit;
    ted->insertHtml("<center><img src='"+QString(":/img/logo.png")+"' width='90' height='72'/><b><font size='9'>Logo Text</font></b></center>");
    ted->document()->print(p);
}

On pushing the print button, this dialog appears:

As you can see the content is spread all over the page. Then I click the page setup button on the preview dialog and this appears:

without changing anything, I click OK and then the preview becomes correct:

The question is that how to correct the preview by code?

回答1:

Use QTextDocument instead of a QTextEdit, the latter is a widget, which makes the output depend on resizing.



回答2:

Add a QPageSetupDialog to show before preview.



回答3:

I had the same issue. Apparently, pressing the OK button of the page setup dialog changes the resolution. To fix this, I change the resolution back in the method which calculates the print preview:

dialog = QPrintPreviewDialog()
dialog.paintRequested.connect(self.print)
dialog.exec_()

def print(self, printer):
    printer.setResolution(300)
    painter = QPainter()
    painter.begin(printer)
    ...


标签: qt printing qt4