Skip to content

Changing Input value doesn't update cursor position #5811

@TomJGooding

Description

@TomJGooding

Changing the Input value doesn't update the cursor position, which can result in an 'invalid' cursor position when the new value is shorter.

Here's a quick example to demonstrate:

from textual.app import App, ComposeResult
from textual.geometry import clamp
from textual.widgets import Button, Input, Label


class ExampleApp(App):
    def compose(self) -> ComposeResult:
        yield Label("[b]Enter a number between 1-10:[/]")
        yield Input(
            "999999999999999999999",
            type="integer",
            select_on_focus=False,
        )

        yield Label("[dim]The input value will be clamped after being submitted.[/]")
        yield Label("[dim]Notice that the cursor seems to disappear.[/]")

        yield Button("Check cursor position", variant="warning")

    def on_input_submitted(self, event: Input.Submitted) -> None:
        clamped_value = clamp(int(event.value), 1, 10)
        event.input.value = str(clamped_value)

    def on_button_pressed(self) -> None:
        cursor_position = self.query_one(Input).cursor_position
        severity = "error" if cursor_position > 2 else "information"
        self.notify(
            str(cursor_position),
            title="Cursor position",
            severity=severity,
        )


if __name__ == "__main__":
    app = ExampleApp()
    app.run()

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions