[solved] Get a screenshot of a QPlainTextEdit's content?



  • hello,

    I want to be able to get a screen shot of the QPlainTextEdit;s content.

    I tried
    qplaintext->viewport()->render(&painter ...);
    but this only generate a screenshot of the visible part of the QPlainTextEdit.

    later I leart that viewport() is just the visible part of the QAbstractScrollArea, to get the content, I need to call

    QScrollArea->widget();

    but QPlainTextEdit is not based on QScrollArea, there is no widget() function.

    I also tried render QTextDocument directly, by calling drawDocument(), but somehow the image I got is corrupted.

    do you know any example of doing this? Thanks.



  • found one solution here, but as it says, it can't preserve the color of the plainTextEdit widget

    https://stackoverflow.com/questions/26794080/how-to-render-qplaintextedit-content-to-qpixmap-with-colors

    I hope to have color too.



  • I think overriding the paintEvent() is the right idea. I am not aware of any other method (that is not external to the program at least). I use this approach myself to create images of graphs rendered to a custom widget.

    bq. qplaintext->viewport()->render(&painter …);
    but this only generate a screenshot of the visible part of the QPlainTextEdit.

    If you take this one step further and draw the frame or border of the widget you should end up with what you are looking for. Following the QStyle source code you can see how to draw the primitives for this widget.

    Note: If the target size of the image is different then the size of the widget the contents will probably look different. This could be good or bad depending on what your goal is.



  • I have found a solution after studying QPlainTextEdit's paintEvent

    @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();
    }
    

    }@


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.