I print a widget (a tab from a QTabWidget) with its content with this code :
void MainWindow::print()
{
quint8 tabIndex = quint8(ui->tabWidget->currentIndex());
CharacterSheetWidget* widget = dynamic_cast< CharacterSheetWidget* >( ui->tabWidget->widget(tabIndex) );
QString filePath = QFileDialog::getSaveFileName(this, QString(tr("Print as PDF...")), QString(), "PDF file (*.pdf)");
if(filePath.isEmpty())
return;
QPrinter printer;
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName(filePath);
printer.setPaperSize(QPrinter::A4);
printer.setResolution(300);
printer.setFullPage(false);
printer.setPageMargins(5, 5, 5, 5, QPrinter::Millimeter);
QString originalStyle = widget->styleSheet();
widget->setStyleSheet("background-color:white;");
QPainter painter;
painter.begin(&printer);
double xscale = printer.pageRect().width() / double(widget->width());
double yscale = printer.pageRect().height() / double(widget->height());
double scale = qMin(xscale, yscale);
painter.translate(printer.paperRect().center());
painter.scale(scale, scale);
painter.translate(- widget->width()/ 2, - widget->height()/ 2);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
widget->render(&painter);
painter.end();
widget->setStyleSheet(originalStyle);
}
but it prints it with a lot of space on the right and on the bottom. I would like to print it with the minimal content area.
For example on this image, you see that it prints the red area in the pdf, I would like it prints the blue area.
How should I do (if you need more information, please tell me) ?
By the way, I founded a solution : Before "QPainter painter;", I added this code :
QSize minSize = widget->minimumSizeHint();
int minWidth = minSize.width();
int minHeight = minSize.height();
And replaced all widget->width() and widget->height by minWidth and minHeight.