Claude
Skills
Sign in
Back

textual-data-display

Included with Lifetime
$97 forever

Display structured data in Textual using tables, lists, trees, and scrollable containers. Use when rendering data tables, building list views, displaying hierarchical data, scrolling large content, pagination, and efficient rendering of large datasets. Covers DataTable, ListView, Tree, and scrolling patterns.

Writing & Docs

What this skill does


# Textual Data Display

## Purpose
Efficiently display and interact with structured data using Textual's data widgets. These widgets handle selection, scrolling, and large datasets with excellent performance.

## Quick Start

```python
from textual.widgets import DataTable, Static
from textual.app import ComposeResult

class TableWidget(Static):
    """Display data in a table."""

    def compose(self) -> ComposeResult:
        yield DataTable()

    async def on_mount(self) -> None:
        """Initialize table with data."""
        table = self.query_one(DataTable)

        # Add columns
        table.add_column("Name", key="name")
        table.add_column("Status", key="status")
        table.add_column("CPU %", key="cpu")

        # Add rows
        table.add_row("Agent-1", "Running", "45.2", key="agent-1")
        table.add_row("Agent-2", "Idle", "12.5", key="agent-2")
        table.add_row("Agent-3", "Running", "78.9", key="agent-3")
```

## Instructions

### Step 1: Use DataTable for Tabular Data

DataTable is the most powerful widget for structured data:

```python
from textual.widgets import DataTable
from textual.app import ComposeResult
from typing import Callable

class DataTableWidget(Static):
    """Widget for displaying tabular data."""

    def compose(self) -> ComposeResult:
        yield DataTable(id="data-table")

    async def on_mount(self) -> None:
        """Initialize table."""
        table = self.query_one("#data-table", DataTable)

        # Configure table
        table.show_header = True        # Show column headers
        table.show_row_labels = True    # Show row numbers
        table.fixed_rows = 1            # Fix header row

        # Add columns with optional width
        table.add_column("ID", key="id", width=8)
        table.add_column("Name", key="name", width=20)
        table.add_column("Status", key="status", width=15)
        table.add_column("Updated", key="updated", width=20)

        # Add rows
        data = [
            ("1", "Agent-1", "Running", "2024-01-15 10:30:45"),
            ("2", "Agent-2", "Idle", "2024-01-15 09:15:20"),
            ("3", "Agent-3", "Error", "2024-01-15 08:45:10"),
        ]

        for row_data in data:
            table.add_row(*row_data, key=row_data[0])

    async def get_selected_row(self) -> tuple | None:
        """Get currently selected row data.

        Returns:
            Tuple of row values or None if no selection.
        """
        table = self.query_one("#data-table", DataTable)

        if table.cursor_row is not None:
            row_key = table.cursor_row
            row = table.get_row(row_key)
            return row if row else None

        return None

    async def clear_table(self) -> None:
        """Clear all data rows (keeps header)."""
        table = self.query_one("#data-table", DataTable)
        table.clear()

    async def add_row(self, *values: str, key: str | None = None) -> None:
        """Add a row to table."""
        table = self.query_one("#data-table", DataTable)
        table.add_row(*values, key=key)

    async def update_row(self, row_key: str, *values: str) -> None:
        """Update existing row."""
        table = self.query_one("#data-table", DataTable)
        table.update_row(row_key, *values)
```

**DataTable Features:**
- Columns with optional widths and keys
- Row keys for easy lookup
- Cursor movement (up/down arrows)
- Single/multiple selection modes
- Sortable columns
- Fixed header rows
- Efficient rendering of large datasets

### Step 2: Handle DataTable Selection Events

Respond to user interactions:

```python
from textual.widgets import DataTable, Static
from textual import on

class SelectableTableWidget(Static):
    """Table with selection handling."""

    def compose(self) -> ComposeResult:
        yield DataTable(id="table")

    async def on_mount(self) -> None:
        """Initialize table."""
        table = self.query_one("#table", DataTable)
        table.add_column("Item")
        table.add_column("Value")

        for i in range(5):
            table.add_row(f"Item {i}", f"Value {i}", key=str(i))

    @on(DataTable.RowSelected)
    async def on_row_selected(self, event: DataTable.RowSelected) -> None:
        """Handle row selection."""
        row_key = event.cursor_row
        table = self.query_one("#table", DataTable)

        # Get row data
        row_data = table.get_row(row_key)
        self.app.notify(f"Selected: {row_data}")

    @on(DataTable.RowHighlighted)
    async def on_row_highlighted(self, event: DataTable.RowHighlighted) -> None:
        """Called as cursor moves (preview)."""
        row_key = event.cursor_row
        # Can use for hovering effects

    @on(DataTable.CellSelected)
    async def on_cell_selected(self, event: DataTable.CellSelected) -> None:
        """Handle specific cell selection."""
        row_key = event.cursor_row
        column_key = event.cursor_column
```

**DataTable Events:**
- `RowSelected` - Row clicked/selected
- `RowHighlighted` - Row cursor moved over
- `CellSelected` - Specific cell selected
- `CellHighlighted` - Cell cursor moved over

### Step 3: Use ListView for Simple Lists

For simple lists with less overhead:

```python
from textual.widgets import ListView, ListItem, Static
from textual.app import ComposeResult
from textual import on

class ListViewWidget(Static):
    """Simple list view."""

    def compose(self) -> ComposeResult:
        yield ListView(id="list")

    async def on_mount(self) -> None:
        """Populate list."""
        list_view = self.query_one("#list", ListView)

        items = ["Item 1", "Item 2", "Item 3", "Item 4"]

        for item_text in items:
            await list_view.append(
                ListItem(Static(item_text))
            )

    @on(ListView.Selected)
    async def on_item_selected(self, event: ListView.Selected) -> None:
        """Handle item selection."""
        selected_item = event.item
        index = event.selection_index

        self.app.notify(f"Selected item {index}")

    async def get_selected(self) -> str | None:
        """Get selected item."""
        list_view = self.query_one("#list", ListView)

        if list_view.index is not None:
            item = list(list_view.children)[list_view.index]
            if isinstance(item, ListItem):
                # Extract text from ListItem
                child = list(item.children)[0]
                if isinstance(child, Static):
                    return child.render_str()

        return None
```

**ListView vs DataTable:**
- `ListView` - Simpler, lighter weight, for lists of items
- `DataTable` - More powerful, columnar data, selection handling

### Step 4: Use Tree for Hierarchical Data

Display tree/nested structures:

```python
from textual.widgets import Tree, Static
from textual.app import ComposeResult
from textual import on

class TreeWidget(Static):
    """Display hierarchical data."""

    def compose(self) -> ComposeResult:
        tree = Tree("Root")
        tree.root.expand()

        # Add branches
        agents_branch = tree.root.add("Agents")
        agents_branch.add("Agent-1")
        agents_branch.add("Agent-2")
        agents_branch.add("Agent-3")

        settings_branch = tree.root.add("Settings")
        settings_branch.add("General")
        settings_branch.add("Advanced")
        settings_branch.add("About")

        yield tree

    @on(Tree.NodeSelected)
    async def on_node_selected(self, event: Tree.NodeSelected) -> None:
        """Handle node selection."""
        node = event.node
        label = node.label
        self.app.notify(f"Selected: {label}")

    @on(Tree.NodeExpanded)
    async def on_node_expanded(self, event: Tree.NodeExpanded) -> None:
        """Handle node expansion."""
        node = event.node
        # Load children on demand
        pass

    @on(Tree.NodeCollapsed)
    async def on_node_collapsed(self, event: Tree.NodeCollapsed) -> None:
        """Handle node collapse."""
       

Related in Writing & Docs