make child widget get the input keypress with urwid on python

326 Views Asked by At

I can make a widget inside another widget, as example an urwid.Frame father could have as body an urwid.Pile widget as child. In this situation, the father should process some input keys when the child have to treat some specific others keys.

Like in this functional example:

import urwid


class NewFrame(urwid.Frame):
    def __init__(self, givenBody):
        super().__init__(urwid.Filler(givenBody, "top"))

    def keypress(self, size, key):
        if key  in ('f'):
            print("We are in NewFrame object")

        return super(NewFrame, self).keypress(size, key)


class NewPile(urwid.Pile):
    def __init__(self, givenList):
        super().__init__(givenList)

    def keypress(self, size, key):
        if key  in ('p'):
            print("We are in NewPile object")

        return super(NewPile, self).keypress(size, key)



master_pile = NewPile([
    urwid.Text("foo"),
    urwid.Divider(u'─'),
])


frame = NewFrame(master_pile)

loop = urwid.MainLoop(frame)
loop.run()

When I press f I could see the Text widget “We are in NewFrame”. But when I press p, the NewPile text doesn’t appear and nothing happens.

So, how could I make the child widget get input keys, especially when they are not matched by the .keypress() method of the parent?

2

There are 2 best solutions below

1
On

In NewFrame's keypress() method call master_pile.keypress(), as below:

def keypress(self, size, key):
    if key  in ('f'):
        print("We are in NewFrame object")

    #return super(NewFrame, self).keypress(size, key)
    master_pile.keypress(size, key)
0
On

From what I can read from the documentation (http://urwid.org/manual/widgets.html#pile-widgets) a Pile widget is only selectable when it contains another selectable widget (which it doesn't in your example).

You should be able to override this behavior in your subclass by overriding selectable() to make it always selectable.

I think Urwid will never call keypress when a widget is not selectable, because widgets are only required to implement keypress when thet are selectable (http://urwid.org/reference/widget.html#urwid.Widget.selectable).