Morpheus
Morpheus

Reputation: 1750

How to render QPlainTextEdit content to QPixmap with colors?

I was successfully using following code to render the content of a QTextEdit to QPixmap. But this fails for QPlainTextEdit. When I use QPlainTextEdit instead of QTextEdit, it rendered 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 render the content of a QPlainTextEdit with colors? Please note,

I'm using Qt4.8.5, VS2008, Windows7

Upvotes: 3

Views: 754

Answers (1)

Bill Yan
Bill Yan

Reputation: 3468

after investigation, I have found a solution.

basically, the QPlainTextEdit widget only draws the part of the content that is visible. Therefore, we can't use QWidget->render to get the entire content rendered. But we can do this by a modified version of the QPlainTextEdit's 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();
    }
}

Upvotes: 4

Related Questions