文本编辑行背景颜色

Kra*_*rab 0 qt qml

是否可以为文本编辑的特定行设置背景颜色(例如单击行时)?

我的 TextEdit 宽度为 500px,行数为 10 行。我将单击第 5 行,该行是空行,但我仍然想更改整行的背景颜色。是否可以?

我需要知道是否可以使用 Qt 和 Qml 开发完全定制的代码编辑器。

Ole*_*ber 5

这是一个依赖于文本编辑的光标矩形的解决方案:

FocusScope {
    id: root
    property alias font: textEdit.font
    property alias text: textEdit.text

    Rectangle {
        color: "lightyellow"
        height: textEdit.cursorRectangle.height
        width: root.width
        visible: root.focus
        y: textEdit.cursorRectangle.y
    }

    TextEdit {
        id: textEdit
        anchors.fill: parent
        focus: true
     }
}
Run Code Online (Sandbox Code Playgroud)

原答案:

这是我的概念验证解决方案。它是一个突出TextEdit显示当前行的自定义组件。它缺乏适当的行高计算,但如果仅使用一种字体大小,则可以对其进行硬编码,也可以从QFontMetrics获取。

import QtQuick 2.3

Item {
    id: root
    property alias font: textEdit.font
    property alias text: textEdit.text

    Column {
        anchors.fill: parent
        Repeater {
            model: root.height / root.lineHeight
            Rectangle {
                color: index === textEdit.currentLine ? "lightyellow" : "transparent"
                height: root.lineHeight
                width: root.width
            }
        }
    }

    TextEdit {
        id: textEdit

        property int currentLine: text.substring(0, cursorPosition).split(/\r\n|\r|\n/).length - 1
        // FIXME: Use proper line height (e.g. from QFontMetrics)
        property int lineHeight: font.pixelSize + 2

        anchors.fill: parent
     }
}
Run Code Online (Sandbox Code Playgroud)

如果您想突出显示空行,那么您需要处理鼠标单击和键盘事件并手动更改相应矩形的颜色。