How to convert QPlainTextEdit to QPixmap with colors?
I have successfully used the following code to render the content of a QTextEdit to a QPixmap. But that doesn't work for QPlainTextEdit. When I use QPlainTextEdit instead of QTextEdit, it displays the content without any colors (all in black / white).
QPixmap* pixmap = new QPixmap(width, height);
QPainter* painter = new QPainter(pixmap);
painter->fillRect( 0, 0, width, height, QColor(247, 247, 247) );
painter->setRenderHints(QPainter::SmoothPixmapTransform |
QPainter::HighQualityAntialiasing |
QPainter::TextAntialiasing);
m_pTextEdit->document()->drawContents(painter);
How can we display the contents of a QPlainTextEdit with colors? Note,
- If we set the text as html in the QPlainTextEdit then it generates colored output.
- I am using a function
QSyntaxHighlighter::setFormat
to set text colors.
I am using Qt4.8.5, VS2008, Windows7
+3
source to share
1 answer
after researching i found a solution.
basically, the QPlainTextEdit widget only draws part of the visible content. Therefore, we cannot use QWidget-> render to get all the content. But we can do it with a modified version of the QPlainTextEdit PaintEvent function:
void TextEditor::getScreenshot(QPixmap &map)
{
QPainter painter(&map);
int offset = 0;
block = document()->firstBlock();
while (block.isValid())
{
QRectF r = blockBoundingRect(block);
QTextLayout *layout = block.layout();
if (!block.isVisible())
{
offset += r.height();
block = block.next();
continue;
}
else
{
layout->draw(&painter, QPoint(0,offset));
}
offset += r.height();
block = block.next();
}
}
+4
source to share