Please nominate your Qt Champions for 2021!

Rendering custom widget to high-resolution QImage

  • I have a custom widget (QWidget subclass) which paints itself via reimplemented paintEvent and is able to scale automatically to any resolution. There are no child widgets, everything is custom-painted. I need to get a high-resolution image of this widget to insert it to QTextDocument.

    I have added the following method to the widget:

    @QImage MyWidget::getImage()
    QImage image(this->size(), QImage::Format_ARGB32);
    this->render(&image, QPoint(), QRegion(), QWidget::DrawChildren);
    return image;

    In the method that creates QTextEdit I have the following piece of code:

    @QTextDocument* document = new QTextDocument();
    document->addResource(QTextDocument::ImageResource, QUrl("myreport://test.png"),
    QString reportHTML;
    // Here is the code for generating report in HTML format
    reportHTML = reportHTML.arg("< img src="myreport://test.png" height="500" width="400" />");

    It works, but the image has the same resolution as the original widget (the image shown in QTextEdit is scaled according to 'height' and 'width' attributes of 'img' tag, but it is unimportant). Is it possible to render the widget to a high-DPI image (suitable for printing), preferably with physical size and DPI defined in advance?

  • There is a technique called tiled rendering, when working with OpenGL. Maybe you can transform the idea:
    .) Zoom by a factor computed from the print size and the required DPI.
    .) Having the widgets size in pixel and the print size in pixel you can compute how many tiles (screenshot of the viewport) in x- and y-direction you need.
    .) Shift your magnified scene (~document) thru the viewport (~widget) and grab the tiles, which you paste in a large (Q)image.

Log in to reply