QTextFormat::FullWidthSelection but for multiple lines?

  • The Code Editor Example shows how to highlight the full width of the current line: https://doc.qt.io/qt-5/qtwidgets-widgets-codeeditor-example.html

    It does this using QTextFormat::FullWidthSelection as follows:

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

    For things that display as multiple lines due to word wrapping, I would like it to highlight every line that is a part of the current block (I think that is the right terminology for it). But QTextFormat::FullWidthSelection doesn't seem to do that. It's only highlighting the current line, one line at a time.

    I tried highlighting the block as a whole instead, but that's not the same behavior as highlighting the full width of the line(s) themselves and I'm struggling to find if there's a way to manually recreate the selection behavior of QTextFormat::FullWidthSelection but for an entire block.

  • I think I figured out a solution. Could probably be a bit cleaner, but this seems to work ok so far. Basically am iterating through the block's lines and do full width selection for each.

    QTextCursor cursor = textCursor();
    for (int i = 0; i < cursor.block().lineCount(); i++)
        QTextEdit::ExtraSelection selection;
        QColor lineColor = QColor(Qt::lightGray);
        selection.format.setProperty(QTextFormat::FullWidthSelection, true);
        selection.cursor = cursor;
        if (i + 1 < cursor.block().lineCount())

Log in to reply