View Full Version : QPrinter and QPrintDialog

21st March 2016, 10:39
Greetings everyone!
I'm having a trouble with printing via Qt.
What I want - is to print the viewable content of MainWindow using QPrint. I have printed test sheets using this code:

void MainWindow::setup_print(void)
dialog = new QPrintDialog(&printer, this);
if (dialog->exec() == QDialog::Accepted)
QPainter painter( &printer );

painter.setPen( Qt::black );

for( int page=0; page<5; page++ )
painter.drawRect( printer.pageRect() );
painter.drawLine( printer.pageRect().topLeft(), printer.pageRect().bottomRight() );
painter.drawLine( printer.pageRect().topRight(), printer.pageRect().bottomLeft() );
painter.drawRect(this->contentsRect() );
QRectF textArea(
printer.pageRect().left() +printer.resolution() * 0.5,
printer.pageRect().top() +printer.resolution() * 0.5,
printer.pageRect().width() -printer.resolution() * 1.0,
printer.pageRect().height()-printer.resolution() * 1.5 );

painter.drawRect( textArea );

painter.drawText( textArea, Qt::AlignTop | Qt::AlignLeft, QString( "Page %1" ).arg( page+1 ) );

if( page != 4 )


the "printer" object is mainwindow class member.
The problem is that I have no idea how to get the content of mainwindow be represented as a QPainter object.
Can anyone help me with this please?

21st March 2016, 11:00
Well, it is obviously very uncommon to print a widget as screen and printer usually have widely different visual properties, but have you tried QWidget::render()?


25th March 2016, 11:59
Thank you very much! That has worked. But now I encountered another problem.
When I'm calling QPrintPreviewDialog, there is two pages, thow I rendered only my central widget. So I have one page with my central widget and another page empty.
Also the Image is printed correctly on the page only if I open the app in fullscreen. If I call my app and it is not stretched to full screen than I see onle part of it on the first page.
I provide the code of my print preview SLOT and connects.

connect(prev_dialog, SIGNAL(paintRequested(QPrinter*)), this, SLOT(print_preview()));
connect(ui->actionPrint_Preview, SIGNAL(triggered(bool)), this, SLOT(preview_called()));
void MainWindow::print_preview(void)
QPainter painter(&printer);

/*if (prev_dialog->exec() == QDialog::Accepted)


void MainWindow::preview_called(void)

Thank you again for helping me to deal with this.