Rendering superclass widget to pixmap in paintEvent

  • So I had this code from a Qt 4 version of my software that used to work. I was able, from my text editor class that inherits from QPlainTextEdit, to override paintEvent() and have the QPlainTextEdit class render to a pixmap from within my paintEvent() function. Then, I could manipulate the pixmap's image however I wanted before drawing it to QPlainTextEdit's viewport. In this case, I had applied a fade effect of the text at the bottom of the viewport area, just like how Byword gracefully fades the text at the bottom of the editor, while preserving whatever background the editor had (which could include transparency/alpha effects in its stylesheet).

    The way I had achieved this in Qt 4 was to call QPainter::setRedirected() on QPlainTextEdit's viewport and redirect it to my pixmap before calling QPlainTextEdit::paintEvent(). You can see my code for this below.

    Unfortunately, with Qt 5, the QPainter::setRedirected() function is now obsolete. In fact, it's so obsolete that it's only implementation involves printing a warning that you should use QWidget::render() instead. However, I cannot use QWidget::render() from within paintEvent(). This will cause recursion on paintEvent(), and the code will fail. I've tried having paintEvent emit a signal to which I connect via a queued connection, and then drawing. But it gets so complicated, and now I'm having issues when I resize the window. I feel it is best to do all the rendering from within paintEvent(). It is also yields the best performance.

    Can anyone think of a reasonable alternative to draw the QPlainTextEdit to the pixmap, now that I can't use QPainter::setRedirected(), and which doesn't involve recursive calls to paintEvent (a la QWidget::render)?

    Thanks in advance!

    void MyTextEditor::paintEvent(QPaintEvent* e)
        QPixmap pixmap(viewport()->size());
        QPainter::setRedirected(viewport(), &pixmap);
        // Gradually fade the text at the bottom of the pixmap image.
        QPainter painter(&pixmap);
        // Does some image manipulation here.
        // Draw the pixmap to the text editor's viewport.
        painter.drawPixmap(viewport()->rect(), pixmap);

  • Have you found a solution yet? I'm having the same problem and got stuck in the same spot.

    Almost got excited when I stumbled across setRedirected(), just to find out it's obsolote the next minute.

Log in to reply

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