OptionList with only one parameter does not return highlighted #2857
-
I subclassed OptionList, added an on_key callback, and noticed that if the list contains only one option, the highlighted property always None.
In
|
Beta Was this translation helpful? Give feedback.
Replies: 4 comments
-
I'd expect this behaviour, which doesn't have anything to do with just having one option. If you create an See this in action with this little app, which creates an from textual import on
from textual.app import App, ComposeResult
from textual.containers import Vertical
from textual.widgets import OptionList, TextLog
from textual.widgets.option_list import Option
class OptionListApp(App[None]):
CSS = """
OptionList {
height: 4fr;
}
TextLog {
height: 1fr;
}
"""
def compose(self) -> ComposeResult:
with Vertical():
yield OptionList()
yield TextLog()
def on_mount(self):
for n in range(20):
self.query_one(OptionList).add_option(Option(f"Here is option {n}"))
self.log_highlighted()
@on(OptionList.OptionHighlighted)
def log_highlighted(self) -> None:
highlighted = self.query_one(OptionList).highlighted
self.query_one(TextLog).write(f"Highlighted: {highlighted!r}")
if __name__ == "__main__":
OptionListApp().run() |
Beta Was this translation helpful? Give feedback.
-
@CognitiveDisson As already mentioned, if there is no option selected, it should print |
Beta Was this translation helpful? Give feedback.
-
The issue was that the OptionList didn't have an opertunity to process the key bindings. Responding to the This code reproduces the issue (and includes the solution). from textual.app import App, ComposeResult
from textual.widgets import OptionList
from textual.widgets.option_list import Option
from textual import events
from textual import on
class ListWidget(OptionList):
def on_mount(self) -> None:
self.add_option(Option("1"))
def on_key(self, event: events.Key) -> None:
print(f"highlighted: {self.highlighted}")
@on(OptionList.OptionHighlighted)
def highlight_changed(self, event: OptionList.OptionHighlighted) -> None:
print(f"highlighted (change): {self.highlighted}")
class TestApp(App):
def compose(self) -> ComposeResult:
yield ListWidget()
app = TestApp()
app.run() |
Beta Was this translation helpful? Give feedback.
-
Thanks for helping solve that issue. The suggested solution works for me. |
Beta Was this translation helpful? Give feedback.
The issue was that the OptionList didn't have an opertunity to process the key bindings. Responding to the
OptionList.OptionHighlighted
event as @davep suggested will ensure that your code runs when the highlight changes.This code reproduces the issue (and includes the solution).