问题
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 ?
回答1:
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.
回答2:
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");
回答3:
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.
来源:https://stackoverflow.com/questions/24284025/rich-text-to-image-in-qt