我有一个QML TextEdit元素,我计划添加一些文本并将光标放在末尾。我的方法:

import QtQuick 1.1

Rectangle {
    color: "black"
    anchors.fill: parent
    focus: false

    TextEdit {
        id: txtCommands

        color: "lightGreen"
        anchors.fill: parent
        textFormat: TextEdit.RichText
        wrapMode: TextEdit.WordWrap

        font.family: "Consolas"
        font.pixelSize: 15
        focus: true

        MouseArea {
            anchors.fill: parent
            focus: false
        }

        Keys.onPressed: {
            console.log(event.text)

            switch (event.key) {
            case 16777234: // LEFT
            case 16777235: // UP
            case 16777237: // DOWN
            case 16777236: // RIGHT
                event.accepted = true
                break;

            case 16777220:  // Enter
                txtCommands.text = txtCommands.text + ">: "
                txtCommands.selectAll()
                txtCommands.cursorPosition = txtCommands.text.length
                break;
            }
        }
    }
}

但这是行不通的。我怎样才能做到这一点?

最佳答案

  • textFormat设置为TextEdit.PlainText,因为否则您会有很多不可见的html代码。
  • 以下代码对我有用。
    Keys.onReturnPressed: {
        event.accepted = true
        txtCommands.text = txtCommands.text + ">: "
        txtCommands.cursorPosition = txtCommands.text.length
    }
    
  • 关于qt - QML如何将文本光标置于TextEdit元素的末尾,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14031070/

    10-12 04:13