How to erase the last char of a LineEdit if user input > limit without the cursor going back?

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

I.e. the limit is 12 and the user introduces 13, the 3 is erased correctly in my code but the cursor goes in front of the 1 (to the left).
I want it to be behind the 1 (otherwise, the code could be broken).

func _on_bill_box_text_changed(new_text):
	bill_box = $bill_box.text
	billNum = int(bill_box)
	if billNum > cent1:
		bill_box.erase(bill_box.length() - 1, 1)
		$bill_box.text = bill_box
:bust_in_silhouette: Reply From: jgodfrey

You can manually set the carat_position, so adding something like this to the end of the above script should work:

$bill_box.caret_position = bill_box.length()

That said, I’m not sure it’s very user friendly, but it should do what you want…

Note, since you didn’t format your code for the forum, it’s difficult to tell where you’re using “_” chars in the var names as they get “eaten” by the forum as italics markup. So, my use of underscores in the above may or may not be correct. Adjust as necessary.

To prevent that confusion, format your posted code via the “{ }” button in the forum editor’s toolbar.

Looking at the LineEdit docs, there’s a better way than what I posted above. Just call delete_char_at_cursor() if the value is > than your max value (12 I think).

So…

if billNum > cent1:
    $bill_box.delete_char_at_cursor()

Additionally, depending on your needs, you might take a look at the SpinBox control, which might be more suitable as it’s designed for numeric input and will allow you to set a min and max value as needed.

jgodfrey | 2020-08-25 23:51

It worked, thanks! I fixed the description now.

Gonz4 L | 2020-08-26 17:31