Important: Please read the Qt Code of Conduct -

QTextDocument: Insert QImage painted with QPainter via QTextCursor and print with maximum printer resolution

  • Hi!

    I like to print a page which contains a headline, an image and a table at the bottom. For this I like to use QTextDocument instead of painting and layouting everthing myself, but I have problems with the image resolution. It seems that the picture gets upscaled before printing. The code below is reduced to the image only to keep things simple.
    The image itself is painted and contains a coordinate system/histogram which addapts internally to the QPainter window() rect and always fills/paints on the full rect. The print preview dialog shows that the image is spread over multiple pages and only shows a little of the left part. I downscaled the image size to 96 dpi, then it fits on a single page but the content is blury and ugly.
    I figured out that the size of the rootFrame size expands after inserting the image as if it was upscaled from 96 dpi to 600 dpi. I tried to set the dpi of the image but without any effect. I need to paint my image with high dpi otherwise it is unreadable after print out.

    I searched the net for advice but couldn't find something similar nor a good code example. Maybe someone has an idea what I am doing wrong, what option I forgot to set or maybe to open a different way to solve my problem.

    @void MainWindow::on_actionPrint_triggered()
    QPrinter printer(QPrinter::HighResolution);
    QPrintPreviewDialog ppd(&printer,this);
    connect(&ppd, SIGNAL(paintRequested(QPrinter*)),this, SLOT(printDocument(QPrinter*)));

    void MainWindow::printDocument(QPrinter *printer)
    QTextDocument document;

    int width  =  printer->pageRect().width();
    int height =  printer->pageRect().height();
    QImage image(width,height,QImage::Format_RGB32);
    int dpm = printer->logicalDpiX() / 0.0254; 
    QPainter p(&image);
    QTextCursor cursor(&document);


Log in to reply