Kivy - Change keyboard cursor position (Caret) after formatting textinput with mask

Asked

Viewed 41 times

2

In a Textinput where the user type the CPF, control the validation and formatting in an on_Text event. After typing the 11 digits and validating the CPF, I format with the mask, however, after formatting, the cursor stands still at the 11th character position. I try to move the cursor using the "cursor" property that Textinput provides, but it has no effect.

Kvlang component creation code:

 TextInputCpf:
        id: txt_cpf
        multiline: False
        size_hint_x: .16
        pos_hint: { 'x':.02 , 'center_y':.66 }

Python code:

class TextInputCpf(TextInput):

    def on_text(self, instance, value):
        if len(value) == 11:
            if uteis.validar_cpf(value):
                self.text = uteis.formatar_cpf(value)
                self.cursor = (len(self.text), 0)

# função simples de formatação
# está no arquivo uteis.py
def formatar_cpf(cpf: str) -> str:
  return '{}.{}.{}-{}'.format(cpf[:3], cpf[3:6], cpf[6:9], cpf[9:11])

1 answer

0

I was able to solve it this way:

    def insert_text(self, substring, from_undo=False):
        if not substring.isnumeric():
            substring = ""

        texto_completo = self.text + substring
        
        if len(texto_completo) == 11:
            if uteis.validar_cpf(texto_completo):
                self.text = uteis.formatar_cpf(texto_completo)
                #self.cursor = (len(self.text), 0)
                self.do_cursor_movement("cursor_end")
                substring = ""
        elif len(texto_completo) > 14:
            self.text = texto_completo[0:14]
            substring = ""

        return super().insert_text(substring, from_undo=from_undo)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.