4

In my application , have a QTextEdit dialog that accepts Rich Text Input. I need to convert this input in to an image for some purpose .

If it was Plain text i could use DrawText associated with the QPainter class . But Rich text cannot be dealt the same way as we don't know the formatting done.

Any suggestions on how to convert ?

J V
  • 515
  • 1
  • 5
  • 15
  • Classes derived from QWidget are able to draw themselves using the [QWidget::render()](http://qt-project.org/doc/qt-4.8/qwidget.html#render) method. Haven't tried it myself. But hopefully it works even if the widget is hidden, so you could pick an arbitrary rectangular size for a copy of the widget without disturbing your input (if you needed). Don't know whether QTextEdit would insist on filling the background or be able to draw transparently, either. But it's a start. – HostileFork says dont trust SE Jun 18 '14 at 11:21

3 Answers3

5

You can grab the content of your QTextEdit in the following way:

QTextEdit te("This is a rich text");
te.resize(100, 100);
QPixmap pix = QPixmap::grabWidget (&te, te.rect());
pix.save("test.png");
Nejat
  • 31,784
  • 12
  • 106
  • 138
vahancho
  • 20,808
  • 3
  • 47
  • 55
  • Grab widget retrieves only the part of text that is visible on screen . Hence if the TextEdit has has multiple paragraphs (scrolling enabled short textbox) - this solution would not be applicable right ? – J V Jun 18 '14 at 14:04
  • Yes. You may try to grab viewport. Or check my solution ;) – Dmitry Sazonov Jun 18 '14 at 14:10
5

You may use QTextEdit::document + QTextDocument::drawContents. You don't need any hacks with rendering widgets, as proposed by other authors, because there may be some problems with anti-aliasing settings.

Dmitry Sazonov
  • 8,801
  • 1
  • 35
  • 61
  • Try to path dimension of an image to `drawContents` method. And, please, post it as a SSCCE. And use directly `myTextEdit->document()->drawContents()` instead of your code overhead. – Dmitry Sazonov Jun 20 '14 at 13:08
2

Alternatively, as also stated in the comments, you can use the widget's render method to draw the widget contents into a pixmap:

void saveImage(QTextEdit* te) {
    QPixmap pixmap(te->size());
    QPainter painter(&pixmap);

    te->render(&painter);
    pixmap.save("test.png");
}

This is essentially what the QPixmap::grabWidget() method does internally.

Andreas Fester
  • 36,091
  • 7
  • 95
  • 123
  • same with rendering . Render retrieves only the part of text that is visible on screen . Hence if the TextEdit has has multiple paragraphs (scrolling enabled short textbox) - only the visible part of the text will be rasterized to an image along with the scroll bar – J V Jun 18 '14 at 14:06