0

I am really new to C++ and QT. I want to print a mainwindow.ui form with printer. For that I have a code like this:

   void MainWindow::on_Button_printer_clicked()
{
    ui->Button_printer->setVisible(0);
    QPrinter printer(QPrinter::ScreenResolution);
    printer.setOutputFormat(QPrinter::PdfFormat);
    printer.setOutputFileName("TestReport.pdf");
    printer.setPageMargins(12, 16, 12, 20, QPrinter::Millimeter);
    printer.setFullPage(false);
    QPainter painter(&printer);
   // double xscale = ;
 //   double yscale = ;
  //  double scale = qMin(xscale, yscale);
    painter.translate(printer.paperRect().center());
  //  painter.scale(scale, scale);
   // painter.translate(-w.width()/ 2, -w.height()/ 2);
    //ui->centralwidget->render(&painter);
    this->render(&painter);
}

However, I do not know what to render current mainwindow form.. I created it via forms. So I think this. render should have worked but it did not. I also tried :

ui->centralwidget->render(&painter);

That did not work too. How can I render the MainWindow form and put instead of "this" in:

this->render(&painter);
  • Does it answer your question https://stackoverflow.com/questions/45467942/how-can-i-print-a-qwidget-in-qt ? – dovahin Jun 23 '20 at 08:21
  • Actually it does not. I have checked it out. In that example, person uses w.render(&painter). But my widget's name is not w... And I do not know what to write instead of w. In my example it is "this". – Günkut Ağabeyoğlu Jun 23 '20 at 08:24
  • Please check main() function. You should have something like MainWindow window; window.show();. That should resolve any of your doubts – dovahin Jun 23 '20 at 08:30
  • In main.cpp I have this: MainWindow w; w.show(); In this case should I use w.render(&painter); ? – Günkut Ağabeyoğlu Jun 23 '20 at 08:34
  • Does this answer your question? [How can I print a QWidget in Qt?](https://stackoverflow.com/questions/45467942/how-can-i-print-a-qwidget-in-qt) – dovahin Jun 23 '20 at 09:17

1 Answers1

1
 ui->Button_printer->setVisible(0);
QPrinter printer(QPrinter::ScreenResolution);
printer.setOutputFormat(QPrinter::PdfFormat);




  printer.setOutputFileName("TestReport.pdf");
  printer.setPageMargins(12, 16, 12, 20, QPrinter::Millimeter);
  printer.setFullPage(false);





  QPainter painter;
       painter.begin(&printer);
       double xscale = printer.pageRect().width() / double(ui->centralwidget->width());
       double yscale = printer.pageRect().height() / double(ui->centralwidget->height());
       double scale = qMin(xscale, yscale);
       painter.translate(printer.paperRect().center());

       painter.scale(scale, scale);
       painter.translate(-width()/2, -height()/2);

       ui->centralwidget->render(&painter);

       painter.end();