PDA

View Full Version : Qt4 : QPainter::setRedirected doesn't work



Ankitha Varsha
20th June 2008, 14:06
Hi,

I am trying to divert the paint operations of a widget to the printer.
But it doesn't seem to work for me.

following is the code.


void print()
{
QPrinter printer;
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName("C:/sample.pdf");
printer.setPageSize(QPrinter::A4);

QPainter::setRedirected(widget, &printer);
QPaintEvent pe(this->rect());
qApp->sendEvent(this, &pe);
QPainter::restoreRedirected(widget);
widget->repaint();
}

Initially, i used widget->repaint() instead of sendevent(). But didnt work either.

If i query redirected() function on the widget before restoring the redirection , it is correctly showing the redirected device as printer. I wonder still why this code doesn't work!

Am i doing any mistake here?

Pls help

-
Ankitha

mcosta
20th June 2008, 16:59
From Qt Documentation



void QPainter::setRedirected ( const QPaintDevice * device, QPaintDevice * replacement, const QPoint & offset = QPoint() ) [static]
Redirects all paint commands for the given paint device, to the replacement device. The optional point offset defines an offset within the source device.
The redirection will not be effective until the begin() function has been called; make sure to call end() for the given device's painter (if any) before redirecting. Call restoreRedirected() to restore the previous redirection.
In general, you'll probably find that calling QPixmap::grabWidget() or QPixmap::grabWindow() is an easier solution.


sendEvent "post" an event then the paintEvent method is invoked after you exit from print.

You can do this


void
MyWidget::print()
{
QPrinter printer;

....

QPixmap myPix = QPixmap::grabWidget(this);

QPainter painter;
painter.begin(&printer);

painter->drawPixmap(0, 0, myPix);

painter.end();
}


QPixmap::grabWidget calls QWidget::paintEvent()

Ankitha Varsha
20th June 2008, 17:52
Hi,
I did this, but it doesn't create sample.pdf as desired.


QPrinter printer;
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName("C:/sample.pdf");
printer.setPageSize(QPrinter::A4);

QPixmap myPix = QPixmap::grabWidget(this);
QPainter painter;
painter.begin(&printer);
painter.drawPixmap(0, 0, myPix);
painter.end();