Search code examples
navigationurwid

How do I know which widget has the focus with urwid?


I am designing a Python interface with urwid and I have several elements that cannot be reached using the cursor navigation keys (i.e. up, down, left and right) and that's indeed what I want. What I'd like is to implement a circular navigation using the Tab key.

There are three components I'd like to reach using this technique — namely a list box that is comprised of radio buttons, an edit box and a button to the right of the edit box. My application is built around a class that derives urwid.WidgetWrap. It contains a frame, the body of which is the listbox, the footer contains the edit box.

So far I've figured out I could trap the Tab key from the main loop's unhandled_input callback... but I have no idea whether it's the way to go or not. Besides I haven't figured out yet how to detect which one of these three widgets has the focus.

Can anyone point me to the right direction?


Solution

  • You probably want to give it a good read in the urwid documentation for the Container widgets.

    Each Container widget is supposed to keep track of which which widgets has the focus in a given moment, and they have the get_focus_path() and get_focus_widgets methods for finding the widgets in focus.

    It looks the default container widgets use this WidgetContainerMixin class which you can inspect to find more.

    As for the right way to implement the focus handling, I believe the best way would be to create custom widgets (either inheriting the existing ones or creating wrappers with urwid.WidgetWrap) which would share the focus handling behavior, but using unhandled_input is probably a good starting point to explore these at least.