6

I have a QML TextEdit element, I plan for append some text and put the cursor at the end. My method:

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

but it doesn't work. How can i do that?

Aquarius_Girl
  • 21,790
  • 65
  • 230
  • 411
Bình Nguyên
  • 2,252
  • 6
  • 32
  • 47

3 Answers3

6
  1. Set textFormat to TextEdit.PlainText because you have lots of invisible html code otherwise.
  2. The following code works for me.

    Keys.onReturnPressed: {
        event.accepted = true
        txtCommands.text = txtCommands.text + ">: "
        txtCommands.cursorPosition = txtCommands.text.length
    }
    
Oleg Shparber
  • 2,732
  • 1
  • 18
  • 19
3

If your TextEdit is not in plain text mode textFormat: TextEdit.PlainText, and is instead set to textFormat: TextEdit.RichText, then
txtCommands.text.length will include the length off all the non-visible html/rtf formatting markup stuff.

The simplest solution is to use txtCommands.length. This property only gives the length of the visible characters.

SpencerB
  • 85
  • 7
1
  1. Create a string temp variable.
  2. temp= TextEdit.getText(0, TextEdit.length)
  3. TextEdit.cursuorPosition += temp.length
Toby Speight
  • 27,591
  • 48
  • 66
  • 103
flash
  • 11
  • 1
  • Welcome to SO. I suggest you to improve your example by reading the [Minimal, Complete and verifiable example](http://stackoverflow.com/help/mcve). – IlGala Dec 14 '15 at 08:27
  • This is the correct answer in my opinion because it preserves the the rich text format property as stated in the question. – Ricardo Cristian Ramirez Feb 20 '21 at 08:19