views:

1252

answers:

2

How do I get Qt to print a complete dialog or window? I could dump the window contents with an external program like xwd and print that, but I would prefer to do it all with Qt.

+5  A: 

Use QPixmap::grabWidget (or QPixmap::grabWindow for external window). Something like this:

QPixmap pix = QPixmap::grabWidget(myMainWindowWidget);

Dunno if you really mean to print it to a printer, if so:

QPrinter printer(QPrinter::HighResolution);
QPainter painter;
painter.begin(&printer);    
painter.drawPixmap (0, 0, &pix);    
painter.end();
corné
pix.grabWidget(myMainWindowWidget) fails for me.I have to use:QPixmap pix = QPixmap::grabWidget(myMainWindowWidget);
PiedPiper
Ah ok, because it's a static method. I edited my answer.
corné
QPixmap::grabWidget was good enough for what I needed, but Ariya's solution QWidget::render() is even better
PiedPiper
+4  A: 

While you can use grabWidget to get the pixmap representation of the dialog, essentially you will be printing the pixels of the pixmap, i.e. the dialog is rasterized a the screen resolution and then scaled to the printer resolution. This may or may not result in some artifacts.

Another way to do it is by using QWidget::render() function that takes a paint device. This way, you can pass your printer as the paint device. The dialog is now "drawn" onto the printer with the the printer's resolution.

Ariya Hidayat