MitchW
MitchW

Reputation: 147

Kivy Selection on Focus

I'm trying to have kivy select the text of a TextInput widget on focus but when I try it seems to select it when it unfocuses and retains the selection. Any ideas how I can select it on focus and on unfocus deselect? I've attached my code below if someone wants to have a play around.

kv file:

<TextInput>:
    size_hint: 0.9, 0.5
    pos_hint: {'center_x': 0.5, 'center_y': 0.5}
    multiline: False

<Button>:
    text: "Press Me"
    size_hint: (0.1, 0.5)
    pos_hint: {'center_x': 0.5, 'center_y': 0.5}

<MainLayout>:
    canvas.before:
        Color:
            rgba: 0.15, 0.15, 0.16, 1
        Rectangle:
            pos: self.pos
            size: self.size

    BoxLayout:
        orientation: 'vertical'
        padding: 10

        BoxLayout:
            padding: 10
            TextInput:
                text: "Directory"
            Button:
                text: "Browse"
                on_press: root.browse_btn()

        BoxLayout:
            padding: 10
            TextInput:
                text: "Prefix"
                on_focus: self.select_all()
            TextInput:
                text: "File"
                on_focus: self.select_all()
            TextInput:
                text: "Suffix"
                on_focus: self.select_all()

        BoxLayout:
            padding: 10
            Button:
                id: button_one
                text: "Confirm"
                on_press: root.confirm_btn()
            Button:
                text: "Cancel"
                on_press: root.cancel_btn()

python file:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty
from kivy.core.window import Window
from kivy.config import Config

Config.set('graphics', 'resizable', 0)


class MainLayout(BoxLayout):
    button_id = ObjectProperty(None)

    def browse_btn(self):
        print("Hey")

    def confirm_btn(self):
        print("Confirm")

    def cancel_btn(self):
        print("Cancel")


class BatchRenameApp(App):
    def build(self):
        self.title = "Batch File Rename"
        Window.size = (750, 250)
        return MainLayout()


if __name__ == '__main__':
    app = BatchRenameApp()
    app.run()

Upvotes: 2

Views: 1008

Answers (1)

John Anderson
John Anderson

Reputation: 39072

Well hidden in the TextInput documentation:

Selection is cancelled when TextInput is focused. If you need to show selection when TextInput is focused, you should delay (use Clock.schedule) the call to the functions for selecting text (select_all, select_text).

So, in your kv, start by importing Clock:

#: import Clock kivy.clock.Clock

Then you can use it in a TextInput rule:

        TextInput:
            text: "Prefix"
            on_focus: Clock.schedule_once(lambda dt: self.select_all()) if self.focus else None

The if self.focus makes sure the select_all only happens when the TextInput gains focus.

Upvotes: 1

Related Questions