ui - getting keyboard input even if a textbox is not focussed
I'm trying to understand how I can catch keyboard inputs in a ui reliably.
When I place a textbox on a form, i need to tap it to make it accept keys.
My use case:
I have a bluetooth keyboard connected to the ipad. (Actually, it's a hardware barcode laser
scanner that acts like a bluetooth keyboard and types any number it scans)
My aim is to accept any number 0-9 and the enter key always, no matter where the focus is.
Whenever enter is recognised, I would then collect the typed number and so something with it.
When developing desktop programs, I can force focus to a textbox from
code, so I don't have to click on it and any scanned number will go in there.
What is the best approach in Pythonista?
I'd prefer not having a textbox at all - and just get all keypresses on a UI.
Hmm, it looks there's an older post about this here - with a good example.
The code linked works after minor changes (print, Python3)
While the example catches keys with a modifier, setting the modifier to 0
makes it possible to catch normal keys and it's possible to catch the
Enter key via chr(13).
So while this looks do-able, the question is if this is a good approach:
One problem with it is that I haven't found out how to trigger updates on
the main view from the function that collects the keys. In my example,
I'm trying to update a label on the view (form) with the number that is scanned.
I've looked at the ui examples, where there's a "sender.superview" that
allows to connect to the other elements of the view.
Here the keyboard control is added as a Subview to the main view, so that doesn't work.
you just want to use begin_editing() on your textfield or textview afte you present it. It not in the docs, so don't feel bad you missed it .
To set tab order requires a but more effort-- see:
For your other question, you can either walk your way up and down the view heirarchy
or, when you set up your textfield, or button, or whatever, you could add an attribute with some key piece of info
textfield=ui.Textfield() mainview.addsubview(textfield) textfield.target=label textfield.action=textfieldaction ... #elsewhere def textfieldaction(sender): sender.target.title='hello'
alternatively, using a custom view class for your main view lets you access the mainview via self.
class myview(ui.View): def __init__(self): self.label =ui.Label() self.add_subview(self.label) .... def textfield_action(self, sender): seld.label.title='hello'
That way, there is one commin place for everything that any ui element needs to know.