TextEdit线条背景颜色

问题描述 投票:0回答:2

是否可以为TextEdit的特定行设置背景颜色(例如,单击行时)?

我将使用宽度为500px且有10行的TextEdit。我将点击第5行,这是空行,但我仍然想要改变整行的背景颜色。可能吗?

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

qt qml
2个回答
3
投票

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

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
     }
}

原答案:

这是我的概念验证解决方案。它是一个自定义的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
     }
}

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


0
投票

您可以使用cursorRectangleTextEditFontMetrics属性来实现此目的:

Item {
    id: root
    height: te.implicitHeight

    FontMetrics {
        id: fontMetrics
        font: te.font
    }

    Rectangle {
        x: 0; y: te.cursorRectangle.y
        height: fontMetrics.height
        width: te.width
        color: "#e7e7e7"
        visible: te.activeFocus
    }

    TextEdit {
        id: te
        anchors.left: parent.left
        anchors.right: parent.right
        anchors.top: parent.top
    }
}

你可以为我的商业项目see the resultMy real world editor for an example

© www.soinside.com 2019 - 2024. All rights reserved.