Search code examples
qmltextareahighlight

Unable to highlight tab character when individually selected in QML TextArea


I'm using the TextArea component in QML for text editing. There's an issue: when I try to select a single tab (\t) character, it doesn't get highlighted. The problem is that the tab character doesn't show up as selected when I try to select it individually.

Here's a code example:

import QtQuick 2.15
import QtQuick.Controls 2.15

ApplicationWindow {
    visible: true
    width: 800
    height: 600

    TextArea {
        id: textArea
        anchors.fill: parent
        text: "Tab" + "\t" + "Highlighting" + "\t" + "Issue"
        selectionColor: "lightblue"
        font.pixelSize: 18
    }
}

When I attempt to select a single tab character (by directly highlighting it with the mouse or using Shift + arrow keys), the tab character doesn't change color. However, if I select the tab along with other text, it gets highlighted properly. Is there a way to make sure that even a single tab character gets highlighted when I select it on its own?


Solution

  • You can do a workaround by calculating and drawing the selection yourself with positionToRectangle() calls, e.g.

    TextArea {
        id: textArea
        anchors.fill: parent
        text: "Tab" + "\t" + "Highlighting" + "\t" + "Issue"
        selectionColor: "transparent" //"lightblue"
        property rect startRect: positionToRectangle(selectionStart)
        property rect endRect: positionToRectangle(selectionEnd)
        font.pixelSize: 18
        background: Item {
            Rectangle {
                x: textArea.startRect.x
                y: textArea.startRect.y
                width: textArea.endRect.x - textArea.startRect.x
                height: textArea.endRect.height
                color: "lightblue"
            }
        }
        Component.onCompleted: select(3, 4)
    }
    

    You can Try it Online!

    Reference: