When a ListItem is Selected how do I return the Label text? #1840
-
Using the example ListView widget code: https://github.com/Textualize/textual/blob/main/docs/examples/widgets/list_view.py ...and this reference in the documentation https://textual.textualize.io/api/list_view/#textual.widgets._list_view.ListView.Selected I should be able to catch the selected object:
However, when I create a |
Beta Was this translation helpful? Give feedback.
Replies: 6 comments 1 reply
-
A If you want the from textual.app import App, ComposeResult
from textual.widgets import ListView, ListItem, Label, Footer
class LabelItem(ListItem):
def __init__(self, label: str) -> None:
super().__init__()
self.label = label
def compose( self ) -> ComposeResult:
yield Label(self.label)
class ListViewExample(App):
CSS_PATH = "list_view.css"
def compose(self) -> ComposeResult:
yield ListView(
LabelItem("One"),
LabelItem("Two"),
LabelItem("Three"),
)
yield Label("Nothing chosen",id="chosen")
yield Footer()
def on_list_view_selected(self, event: ListView.Selected):
self.query_one("#chosen",Label).update(event.item.label)
if __name__ == "__main__":
app = ListViewExample()
app.run() |
Beta Was this translation helpful? Give feedback.
-
@davep Thank You. Your suggestion achieves the outcome I was hoping for. While I have adopted your suggested code, I still seek clarity on how to access the text of a child widget. In the example:
Is there another way to access the text of Label when it's a child of a child using the |
Beta Was this translation helpful? Give feedback.
-
Since this is such a common use case (wanting to get an object associated with a selected item), it would make sense to add this as standard functionality to ListItem to avoid having to always create a subclass. |
Beta Was this translation helpful? Give feedback.
-
You can do something like
|
Beta Was this translation helpful? Give feedback.
-
I ended up using Static for this yield ListItem(Static("My text", name="My text")) You can get the text from def on_list_view_selected(self, event: ListView.Selected) -> None:
list_item = event.item.children[0]
self.notify(f"{list_item.name}") |
Beta Was this translation helpful? Give feedback.
-
The easiest way is to query the ListItem for the Label: yield ListItem(Label("My item"), id="my-item") def on_list_view_selected(self, event: ListView.Selected) -> None:
selected_label = event.item.query_one(Label).renderable |
Beta Was this translation helpful? Give feedback.
A
ListItem
is a container widget, that can contain other widgets; in the example you point at it will contain aLabel
; it could, if you wanted, be any other kind of widget. The point here being that aListItem
doesn't have a label; it's just a container of other things.If you want the
ListItem
s of yourListView
to contain widgets that also let you get a string label back, likely the best approach is to make such a widget of your own. So, taking thelist_view.py
example a little further: