-
|
Hey, I’m struggling to highlight an element when repopulating a ListView with new items. Can someone help me out? The usual thing any clanker suggests is setting the I try to make a nested menu out of ListView, there the visiting status is preserved. Here is minimal example…from textual.app import App
from textual.widgets import ListView, ListItem, Label
data = {
"White Rabbit": {"Lory": {"Eaglet": None}, "Mouse": {"Dodo": None}},
"Duck": {"Bill the Lizard" : None, "Pat": {"Caterpillar": None, "Pigeon": None}},
"Duchess": {"Cook": {"Cheshire Cat": None, "March Hare": None, "Hatter": None}},
"Dormouse": { "Frog-Footman": None, "Fish-Footman": None},
"Mock Turtle": {"King of Hearts": None, "Queen of Hearts": None, "Knave of Hearts": None}
}
class Item(ListItem):
def __init__(self, key):
super().__init__(Label(key))
self.key = key
class Menu(ListView):
def __init__(self, menu_data, path=[]):
super().__init__()
self.data = menu_data
self.path = path
self.history = []
def on_mount(self):
for key in self.data:
self.append(Item(key))
def on_list_view_selected(self, e):
key = e.item.key
if self.data[key]:
self.history.append((self.data, self.path))
self.clear()
self.data = self.data[key]
self.path = self.path + [key]
for k in self.data:
self.append(Item(k))
self.index = 0
def on_key(self, e):
if e.key == "backspace" and self.history:
self.clear()
self.data, self.path = self.history.pop()
for k in self.data:
self.append(Item(k))
self.index = 0
class MyApp(App):
def compose(self):
yield Menu(data)
MyApp().run() |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
|
async def set_items(self, menu_data, path):
await self.clear()
self.data = menu_data
self.path = path
await self.extend([Item(key) for key in self.data])
self.index = 0
self.focus()Then call that helper from the selected/backspace paths. |
Beta Was this translation helpful? Give feedback.
No, I would not explicitly construct
AwaitCompletein the handler. In the version I sketched,set_itemsis anasynchelper, so the call site should just be an async handler andawait self.set_items(...):AwaitCompleteis mainly for APIs that return an optionally-awaitable object; Textual's docs say you are unlikely to need to create it yourself. Textual also awaitsasyncmessage handlers. Docs: https://textual.textualize.io/api/await_com…