The Godot Q&A is currently undergoing maintenance!

Your ability to ask and answer questions is temporarily disabled. You can browse existing threads in read-only mode.

We are working on bringing this community platform back to its full functionality, stay tuned for updates.

godotengine.org | Twitter

0 votes

I need their to be a character limit for the text edit node. I tried:

func _on_TextEdit_text_changed():
    if get_text().length() > character_limit:
        readonly = true

But the problem is that then the text can not be edited again. I want the player to be able to go back and delete text again.

in Engine by (33 points)

1 Answer

+1 vote
Best answer

This seems to work pretty well.

export(int) var LIMIT = 10
var current_text = ''
var cursor_line = 0
var cursor_column = 0

func _on_TextEdit_text_changed():
    var new_text : String = $Control/TextEdit.text
    if new_text.length() > LIMIT:
        $Control/TextEdit.text = current_text
        # when replacing the text, the cursor will get moved to the beginning of the
        # text, so move it back to where it was 
        $Control/TextEdit.cursor_set_line(cursor_line)
        $Control/TextEdit.cursor_set_column(cursor_column)

    current_text = $Control/TextEdit.text
    # save current position of cursor for when we have reached the limit
    cursor_line = $Control/TextEdit.cursor_get_line()
    cursor_column = $Control/TextEdit.cursor_get_column()
by (1,663 points)
selected by

Thank you that works perfectly!

Are there any disadvantages of ignoring the cursor and all?

func cropLineToMaxLength(maxLength: int) -> void:
  var inputText := get_line(0)
  if inputText.length() > maxLength:
    set_line(0, inputText.substr(0, maxLength))


func _on_Input_text_changed() -> void:
  cropLineToMaxLength(3)

And I think it would clarify the purpose if it was connected directly to the respective TextEdit Node instead of to the Control, would it not?

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.