Doing a IntegerField

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By lazlo

I use Godot 3.0.6
I would like to Put a Field that the user of my game can fill with integeters only.
LineEdit and TextEdit are both usefull for text but not for integers.
Would be nice to have a floating Field too.

Only parsing is not an option since i absolutely need an integer
I don’t know if it exists a way to do it or if i need to create a plugin don’t know exactly how to do it.

:bust_in_silhouette: Reply From: p7f

Hi, for doing an integer field, you can modify the lineedit. Just add a LineEdit node to your scene, and attach this script to it:

GODOT 3.0.6

extends LineEdit

var regex = RegEx.new()
var oldtext = ""

func _ready():
    regex.compile("^[0-9]*$")

func _on_LineEdit_text_changed(new_text):
    if regex.search(new_text):
	    oldtext = new_text
    else:
	    text = oldtext
    set_cursor_position(text.length())

func get_value():
    return(int(text))

BE SURE THAT YOU CONNECT LineEdit’s signal text_changed TO FUNCTION ON LineEdit _onLineEdit_text_changed.

GODOT 3.1

extends LineEdit

var regex = RegEx.new()
var oldtext = ""

func _ready():
    regex.compile("^[0-9]*$")

func _on_LineEdit_text_changed(new_text):
    if regex.search(new_text):
	    text = new_text   
        oldtext = text
    else:
	    text = oldtext
    set_cursor_position(text.length())

func get_value():
    return(int(text))

What i’m doing here, is first declaring a regular expresion that only accepts numeric input. When text changes, you check that the text is numeric. If so, you write that text, if not you keep old text. With get_value function you can get the integer value.

BTW, i’ve tested it on godot 3.1 beta 2, cause i dont have currently godot 3.0.6… if it does not work i’ll download that version and try!

p7f | 2019-01-22 11:56

NVM, edited for solution in both versions, tested and works in my pc.

p7f | 2019-01-22 12:02

Thanks for the help didnt knew the existence of regex
in fact it’s pretty simple when you use that tool

lazlo | 2019-01-22 13:53

you are welcome!

p7f | 2019-01-22 13:54

In Godot 4 u have to go with:

set_caret_column(text.length())

Instead of:

set_cursor_position(text.length())

Brotap | 2023-06-24 23:34

:bust_in_silhouette: Reply From: Calinou

You can use a SpinBox node which accepts only integers or floats (depending on the step value you specified).

Actually, this is a better answer. I was so blinded because the question mentioned LineEdit that i didn’t thinl of that!

p7f | 2019-01-23 00:46