Skip to content

Commit 217061c

Browse files
authored
Merge pull request #4384 from MuongKimhong/extend-listview-functionality
added insert, pop and remove_items methods to ListView
2 parents 07e9426 + 1b9e808 commit 217061c

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

src/textual/widgets/_list_view.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,54 @@ def clear(self) -> AwaitRemove:
216216
self.index = None
217217
return await_remove
218218

219+
def insert(self, index: int, items: Iterable[ListItem]) -> AwaitMount:
220+
"""Insert new ListItem(s) to specified index.
221+
222+
Args:
223+
index: index to insert new ListItem.
224+
items: The ListItems to insert.
225+
226+
Returns:
227+
An awaitable that yields control to the event loop
228+
until the DOM has been updated with the new child item.
229+
"""
230+
await_mount = self.mount(*items, before=index)
231+
return await_mount
232+
233+
def pop(self, index: Optional[int] = None) -> AwaitRemove:
234+
"""Remove last ListItem from ListView or
235+
Remove ListItem from ListView by index
236+
237+
Args:
238+
index: index of ListItem to remove from ListView
239+
240+
Returns:
241+
An awaitable that yields control to the event loop until
242+
the DOM has been updated to reflect item being removed.
243+
"""
244+
if index is None:
245+
await_remove = self.query("ListItem").last().remove()
246+
else:
247+
await_remove = self.query("ListItem")[index].remove()
248+
return await_remove
249+
250+
def remove_items(self, indices: Iterable[int]) -> AwaitRemove:
251+
"""Remove ListItems from ListView by indices
252+
253+
Args:
254+
indices: index(s) of ListItems to remove from ListView
255+
256+
Returns:
257+
An awaitable object that waits for the direct children to be removed.
258+
"""
259+
items = self.query("ListItem")
260+
items_to_remove = []
261+
for index in indices:
262+
items_to_remove.append(items[index])
263+
264+
await_remove = self.app._remove_nodes(items_to_remove, self)
265+
return await_remove
266+
219267
def action_select_cursor(self) -> None:
220268
"""Select the current item in the list."""
221269
selected_child = self.highlighted_child

0 commit comments

Comments
 (0)