Search code examples
qtqpainterqprinter

QtTextEdit: text content not rendered to QPainter


I have difficulties rendering the context of a QTextEdit to a painter (which prints to PDF). All other widgets are correctly printed, only the text of the QTextWidget is not.

The widgets look fine in the GUI:

QTextEdit in widget

But the text of the QTextWidget is not printed to the PDF:

enter image description here

The code is quite simple. Perhaps I need to add additional flags? I would like the text to be rendered the same as it looks in the GUI, so a seperate rendering of the text (using textField->document()->drawContents(&painter), is not the best solution)

QTextEdit* textField= ...
// textedit is correctly visible

QPrinter printer(QPrinter::HighResolution);
...
QPainter painter( &printer );
textField->render(&painter, QPoint(), QRegion(), QWidget::DrawChildren);

Solution

  • In the end, a good solution was to directly render the document of the QTextEdit using drawContents(). This is even better, as it renders to vector graphics.

    QTextEdit* textField= ...
    
    // textedit is correctly visible
    QPrinter printer(QPrinter::HighResolution);
    ...
    
    QPainter painter( &printer );
    // textField->render(&painter, QPoint(), QRegion(), QWidget::DrawChildren);
    textField->document()->drawContents(&painter);