Qt4: QPrinter / QPainter only print the first document

Posted by hurikhan77 on Stack Overflow See other posts from Stack Overflow or by hurikhan77
Published on 2010-06-13T12:09:52Z Indexed on 2010/06/13 12:12 UTC
Read the original article Hit count: 385

Filed under:
|
|

In Qt4, I'm initializing the printer in the main.cpp in the following way:

mw->printer = new QPrinter(QPrinter::HighResolution);
mw->printer->setPaperSize(QPrinter::A5);
mw->printer->setNumCopies(2);
mw->printer->setColorMode(QPrinter::GrayScale);

QPrintDialog *dialog = new QPrintDialog(mw->printer, mw);
dialog->setWindowTitle(QObject::tr("Printer Setup"));
if (dialog->exec() == QDialog::Accepted)
{
    mw->printer->setFullPage(TRUE);
    return a.exec ();
}

This works fine for printing the first document from the application:

qDebug("Printing");
QPainter p;
if (!p.begin(printer))
{
    qDebug("Printing aborted");
    return;
}
Q3PaintDeviceMetrics metrics(p.device());
int dpiy = metrics.logicalDpiY();
int dpix = metrics.logicalDpiX();
int tmargin = (int) ((marginTop / 2.54) * dpiy);
int bmargin = (int) ((marginBottom / 2.54) * dpiy);
int lmargin = (int) ((marginLeft / 2.54) * dpix);
int rmargin = (int) ((marginRight / 2.54) * dpix);
QRect body(lmargin, tmargin,
           metrics.width() - (lmargin + rmargin),
           metrics.height() - (tmargin + bmargin));
QString document;
/* ... app logic to write a richtext document */
Q3SimpleRichText richText(QString("<qt>%1</qt>").arg(document),
                          QFont("Arial", fontSize));
richText.setWidth(&p, body.width());
QRect view(body);
int page = 1;
do {
    // draw text
    richText.draw(&p, body.left(), body.top(), view, colorGroup());
    view.moveBy(0, body.height());
    p.translate(0, -body.height());
    // insert page number
    p.drawText(view.right()  - p.fontMetrics().width(QString::number(page)),
               view.bottom() + p.fontMetrics().ascent() + 5,
               QString::number(page));
    // exit loop on last page
    if (view.top () >= richText.height ()) break;
    printer->newPage();
    page++;
} while (TRUE);
if (!p.end()) qDebug("Print painter yielded failure");

But when this routine runs the second time, it does not print the document. It will just print an empty page but still with the page number on it. This worked fine before with Qt3.

© Stack Overflow or respective owner

Related posts about printing

Related posts about qt4