Congratulations to our 2022 Qt Champions!

drawRect in plainTextEdit with qt

  • Hello,
    I try to highlight some lines in a plaintextEdit (example)
    First, i need to show a Rect in the Text edit.
    I add a button to draw a rect

    void form2::on_pushButton_5_clicked()
            QPainter painter(ui->plainTextEdit); //With this, it is the same pb

    The debugger said :

    QWidget::paintEngine: Should no longer be called
    QPainter::begin: Paint device returned engine == 0, type: 1
    QPainter::drawRects: Painter not active

    Some helps Please.
    Thanks for reading.

  • Lifetime Qt Champion

    you cannot draw with painter outside of PainEvent.
    Also you can override plainTextEdit PainEvent and draw a rect but it wont follow
    text like an inserted image at all.
    If you want to color the words, this can work
    but you wont be able to draw rects.

  • I highlight the first line of the text to see what happen

        QTextCursor tmpCursor =ui->plainTextEdit->textCursor();

    After i find "Code Editor Example"
    The construction af the window finish by the code "highlightCurrentLine();"

    void CodeEditor::highlightCurrentLine()
        QList<QTextEdit::ExtraSelection> extraSelections;
        if (!isReadOnly()) {
            QTextEdit::ExtraSelection selection;
            QColor lineColor = QColor(Qt::yellow).lighter(160);
            selection.format.setProperty(QTextFormat::FullWidthSelection, true);
            selection.cursor = textCursor();

    no way to include textCursor(); and !isReadOnly() in the scope ....
    the incude seem correct...

  • Lifetime Qt Champion

    @An-other-french said in drawRect in plainTextEdit with qt:

    no way to include textCursor(); and !isReadOnly() in the scope ....

    What you mean ?
    If CodeEditor is not a subclass of QPlainText then you need something like
    or how ever it has access to the plainTextEdit.

  • obviously yes

  • As we saw in the Qt"s exemple, the highlightCurrentLine function don't highlight the line if it was written in two lines...
    FindBlockByLineNumber gave a different highlightCurrentLine.

    one way is to forbidden the carriage return.
    other is to test if the line carry on or not ...

    An idea?!!

    The purpose is to highlight all lines with the same criterias.
    For example, highlight all lines which contains the word John.

  • Lifetime Qt Champion

    @An-other-french said in drawRect in plainTextEdit with qt:


    Hi, i think it will be another block if written like 2 lines. Just like a paragraph in a
    word processor. so i think you have to check if it continues. However, if you can
    disable CR that would help.

  • for me it s the same block

Log in to reply