Repository navigation
How do you perform On Demand loading for DataTable rows? #5864
Replies: 1 comment 2 replies
|
You can load batches on demand by keeping the pagination state in your app Here is a complete button-triggered example. import asyncio
from textual import work
from textual.app import App
from textual.widgets import Button, DataTable
async def fetch_page(offset, limit):
"""Replace with an async database/API call; this example has 125 rows."""
await asyncio.sleep(0.01)
return [(i, f"Item {i}") for i in range(offset, min(offset + limit, 125))]
class PagedTable(App):
CSS = "DataTable { height: 1fr; }"
page_size = 50
def __init__(self):
super().__init__()
self.offset = 0
self.busy = False
self.finished = False
def compose(self):
yield DataTable()
yield Button("Load more", id="more")
def on_mount(self):
self.query_one(DataTable).add_columns("ID", "Name")
self.request_page()
def on_button_pressed(self, event: Button.Pressed):
if event.button.id == "more":
self.request_page()
def request_page(self):
if self.busy or self.finished:
return
self.busy = True
self.query_one("#more", Button).disabled = True
self.load_page()
@work
async def load_page(self):
try:
rows = await fetch_page(self.offset, self.page_size)
self.query_one(DataTable).add_rows(rows)
self.offset += len(rows)
self.finished = not rows
except Exception as error:
self.notify(str(error), severity="error")
finally:
self.busy = False
self.query_one("#more", Button).disabled = self.finished
if __name__ == "__main__":
PagedTable().run()The button is disabled while a request is running. The offset advances only I tested this as a headless Textual 8.2.8 app: the table grew from 50 to 100 This postpones fetching additional data, but added rows remain stored in the |
Uh oh!
There was an error while loading. Please reload this page.
Hello,
Textual looks like a great project, I am interested in using it, due to its portability. My one requirement is the ability to load rows to a
DataTableon demand. I am familiar with Qts MVC methodology, and itsQTableViewhas methods such ascanFetchMoreandfetchMorefor on demand loading. Is there anything equivalent? Or some recipe to do this with Textual? I'm struggling to find if this is possible, except for one discussion that links to a 3rd party Textual extension. Seems to be not?All reactions