Home > Software design >  How to Make Input Field in kivymd focus agane
How to Make Input Field in kivymd focus agane

Time:12-23

using kivymd to make app for scanning barcode quickly as possible , i created this app with one text field that will take QR code and store it, if user input once , focus will gone and must focus it manually to get another input from user . it is possible to make it take many input without losing his focus?

main.py

from kivymd.app import MDApp
from kivymd.uix.screen import Screen



class Layout(Screen):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
    
    def check(self):
        item = self.ids.qrcode
        print(item.text)
       
        


class Core(MDApp):
    def build(self):
        self.theme_cls.primary_palette = "Green"
        return Layout()

if __name__ == '__main__':
    Core().run()

core.kv

<Layout>:
    cols:1
    MDTextField:
        id: qrcode
        hint_text: "QR Code"
        focus: True
        helper_text: "Enter Shipment QR"
        helper_text_mode: "on_focus"
        icon_right: "qrcode-scan"
        icon_right_color: app.theme_cls.primary_color
        pos_hint:{'center_x': 0.5, 'center_y': 0.9}
        size_hint_x:None
        width:300
        on_text_validate: root.check()

CodePudding user response:

If you put self.ids.qrcode.focus = True in your check method, it will be called too early. You will focus and the focus loss will occur afterward.

You can use Clock.schedule_once(self.refocus_ti) in your check method with the following method:

def refocus_ti(self, *args):
    self.ids.qrcode.focus = True

With the above code, it will refocus the text field after your check method.

Complete code snippet:

# core.kv
<Layout>:
    cols:1
    qrTextInput: qrcode
    MDTextField:
        id: qrcode
        hint_text: "QR Code"
        focus: True
        helper_text: "Enter Shipment QR"
        helper_text_mode: "on_focus"
        icon_right: "qrcode-scan"
        icon_right_color: app.theme_cls.primary_color
        pos_hint:{'center_x': 0.5, 'center_y': 0.9}
        size_hint_x:None
        width:300
        on_text_validate: root.check()
from kivymd.app import MDApp
from kivymd.uix.screen import Screen
from kivy.lang import Builder
from kivy.properties import ObjectProperty
from kivy.clock import Clock

Builder.load_file("kv/core.kv")

class Layout(Screen):
    qrTextInput = ObjectProperty(None)
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
    
    def check(self):
        item = self.ids.qrcode # Or access with self.qrTextInput.text
        print(item.text)        
        Clock.schedule_once(self.refocus_ti)

    def refocus_ti(self, *args):
        self.qrTextInput.focus = True


class Core(MDApp):
    def build(self):
        self.theme_cls.primary_palette = "Green"
        return Layout()

if __name__ == '__main__':
    Core().run()

  • Related