How could I define the text-overflow method of the DataTable cells? #3136
-
Hi, as the title says I want to know how to modify the text overflow method of the cells inside a DataTable widget. If I put text larger than the width of the column, the excess characters are simply discarded as if they were not there in the first place.
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 6 replies
-
That's not strictly true, the value of the cell still contains the full contents even if it overflows the visible width (see example below). Unfortunately looking at how the DataTable is rendered, I'm not sure it is currently possible to display text overflow with ellipsis, or at least not without losing the rest of the content,. But perhaps someone has found a clever workaround! Alternatively you could set from textual import on
from textual.app import App, ComposeResult
from textual.widgets import DataTable, Log
LONG_TEXT = "Lorem ipsum dolor sit amet, consectetur adipisci elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua."
COLUMN_WIDTH = 20
class ExampleApp(App):
CSS = """
DataTable {
height: 50%
}
Log {
height: 50%;
border: double $primary;
}
"""
def compose(self) -> ComposeResult:
yield DataTable()
yield Log()
def on_mount(self) -> None:
log = self.query_one(Log)
log.border_title = "Highlighted Cell Contents"
table = self.query_one(DataTable)
for i in range(3):
table.add_column(
f"Column #{i}",
width=COLUMN_WIDTH, # Explicitly set the column width
)
for _ in range(5):
table.add_row(*["Example short text" for _ in range(3)])
@on(DataTable.CellSelected)
def insert_long_text(self, event: DataTable.CellSelected) -> None:
event.data_table.update_cell_at(
event.coordinate,
LONG_TEXT
# Alternatively you can resize the column width
# to accommodate for the new cell content:
# update_width=True,
)
@on(DataTable.CellHighlighted)
def log_cell(self, event: DataTable.CellHighlighted) -> None:
log = self.query_one(Log)
log.write_line(event.data_table.get_cell_at(event.coordinate))
if __name__ == "__main__":
app = ExampleApp()
app.run() |
Beta Was this translation helpful? Give feedback.
In the end I had to do this
long_text[: min(26, len(long_text)) + "…"
as a simple workaround (this may vary depending the use case). With this the cell will indeed have the data cropped out but I made a relation between the cell idx and the original content that was suposed to be there in the first place (this way I'll be able to recover the text without ellipsis).