4

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?

ugoren
  • 16,023
  • 3
  • 35
  • 65
Noah Watkins
  • 5,446
  • 3
  • 34
  • 47

2 Answers2

3

The accepted solution fails on first key press:

AttributeError: 'SelectableText' object has no attribute 'keypress'

Injecting my own implementation that does nothing makes the error go away, but it also completely borks all keybindings.

I found this and it seems to work just fine:

class SelectableText(urwid.Edit):
    def valid_char(self, ch):
        return False
rr-
  • 14,303
  • 6
  • 45
  • 67
1

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))
Noah Watkins
  • 5,446
  • 3
  • 34
  • 47
  • 1
    This allows it to be selectable, but my impl still tells me that it needs a keypress has no keypress defined. I defined this, but making a Text work for ListBox still doesn't work even with a SimpleFocusListWalker – Lucas Crawford Jun 25 '15 at 22:55