Search code examples
pythonuser-interfaceconsolecursesurwid

Urwid ListBox: How to get fluid focus movement?


I have the following code snippet that shows a list of numbers, and highlights the currently in-focus item:

import urwid

palette = [('header', 'white', 'black'),
    ('reveal focus', 'black', 'dark cyan', 'standout'),]

items = map(lambda x: urwid.Text(`x`), range(500))
items = map(lambda x: urwid.AttrMap(x, None, 'reveal focus'), items)

walker = urwid.SimpleListWalker(items)
listbox = urwid.ListBox(walker)

loop = urwid.MainLoop(listbox, palette)
loop.run()

When I start the program the terminal looks like:

0   <-- highlighted
1
2
3
...

If I press the down button then the view changes to:

1
2
3
4   <-- highlighted
...

I would like a behavior in which 0-3 are highlighted and in-focus before the screen scrolls downward. What is the best way to accomplish this?


Solution

  • The items in the list box need to be selectable. Here is one approach:

    class SelectableText(urwid.Text):
        ...
        def selectable(self):
            return True
    ...
    
    items = map(lambda x: SelectableText(`x`), range(500))