Focus and Blur event #3889
-
I have a Screen with a dock and a Static, I want to switch focus between these 2 widget, I followed the documentation but I can't get it to work. # style
LeftPanel {
dock: left;
width: 20;
}
class LeftPanel(Static):
def compose(self) -> ComposeResult:
yield Static("some text")
def on_focus(self, event: events.Focus):
log("Log something")
class RightPanel(Static):
def compose(self) -> ComposeResult:
yield Static("some new text")
class MyScreen(Screen):
def compose(self) -> ComposeResult:
yield LeftPanel()
yield RightPanel()
def on_key(self, event: events.Key):
if event.key == "ctrl+q":
self.query_one(LeftPanel).focus()
self.query_one(RightPanel).blur()
elif event.key == "ctrl+b":
self.query_one(RightPanel).focus()
self.query_one(LeftPanel).blur() when i hit https://textual.textualize.io/api/widget/#textual.widget.Widget.focus |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
If you're creating a compound widget, you probably want to inherit from |
Beta Was this translation helpful? Give feedback.
-
In addition to what Tom says above, more generally, if you're wanting to focus a particular widget (that can receive focus), you don't need to blur the old one; and if you're going to focus a particular widget using a keystroke you can use a binding and the focus action. As an example of something similar to what you appear to be aiming for: from textual.app import App, ComposeResult
from textual.containers import Horizontal, Vertical
from textual.widgets import Label
class Panel(Vertical, can_focus=True):
DEFAULT_CSS = """
Panel {
border: round red;
}
Panel:focus {
border: round green;
}
"""
class BoundFocusExampleApp(App[None]):
BINDINGS = [
("f1", "focus('left')"),
("f2", "focus('right')"),
]
def compose(self) -> ComposeResult:
with Horizontal():
with Panel(id="left"):
yield Label("This is the left panel (press F1)")
with Panel(id="right"):
yield Label("This is the right panel (press F2)")
if __name__ == "__main__":
BoundFocusExampleApp().run() |
Beta Was this translation helpful? Give feedback.
Static
isn't focussable.If you're creating a compound widget, you probably want to inherit from
Widget
or one of the containers instead.