class DataFrameViewer(SortableViewerMixin, widgets.Widget):
"""Data table with synced column / index headers (MultiIndex spans for pandas).
Clicking a column header emits `sort_requested(column, order)` (`order` is a
`Qt.SortOrder`; clicking the same column again reverses it). With
`sortable=True` (default) the viewer then sorts itself, see `sort_mode`; with
`sortable=False` it only emits the signal, so an application can sort under its
own control (e.g. a memory budget) and call `set_df()` / `set_sort_state()`.
`sort_mode="copy"` (default) replaces the frame by a sorted copy (on the GUI
thread); `sort_mode="permutation"` sorts for display only (a row order of 8 bytes
per row in the holder, no frame copy). The order is computed in a worker thread:
`sorting_changed(True)` while it runs, `sorting_changed(False)` when it was
applied or dropped. Only the latest request is applied, and only if the frame
was not replaced or edited meanwhile; `cancel_sort()` drops a running one.
See `DataFrameModel`.
"""
sort_requested = core.Signal(int, object) # ty: ignore[missing-argument]
sorting_changed = core.Signal(bool) # ty: ignore[missing-argument]
def __init__(
self,
df: Any = None,
*,
sortable: bool = True,
sort_mode: SortMode = "copy",
dtype_icons: bool = True,
**kwargs,
) -> None:
"""Pass a DataFrameHolder to share the frame with other models / widgets."""
super().__init__(**kwargs)
if not self.objectName():
self.setObjectName("cutepandas_dataframe_viewer")
# Indicates whether the widget has been shown yet. Set to True in showEvent.
self._loaded = False
self._dtype_icons = dtype_icons
self._autosized_cols: set[int] = set()
if isinstance(df, DataFrameHolder):
self.holder = df
else:
self.holder = DataFrameHolder(df, parent=self)
# Set up DataFrame TableView and Model
self.table_data = DataTableView(self.holder, parent=self)
data_model = self.table_data.get_model(skip_proxies=True)
data_model.set_sort_mode(sort_mode)
self.sorter = SortController(data_model, sortable=sortable, parent=self)
self._connect_sorter()
self.set_size_policy("expanding", "expanding")
self.table_data.selectionModel().selectionChanged.connect(
self._on_selection_changed
)
# Create headers
self.table_columns = HeaderView(
orientation=constants.HORIZONTAL,
parent=self,
show_dtype_icons=dtype_icons,
)
self.table_columns.clicked.connect(self.on_clicked)
self.sorter.sort_state_changed.connect(
lambda _state: self.table_columns.viewport().update()
)
self.table_index = HeaderView(orientation=constants.VERTICAL, parent=self)
self.table_columns.selectionModel().selectionChanged.connect(
self.on_column_selection_changed
)
self.table_index.selectionModel().selectionChanged.connect(
self.on_index_selection_changed
)
# Set up layout
self.layout_grid = self.set_layout("grid", margin=0, spacing=0)
# room for the 1 px outer border painted by paintEvent
self.layout_grid.setContentsMargins(1, 1, 1, 1)
# Link scrollbars
self.table_data.h_scrollbar.valueChanged.connect(
self.table_columns.h_scrollbar.setValue
)
self.table_data.h_scrollbar.valueChanged.connect(self._autosize_visible_columns)
self.table_data.v_scrollbar.valueChanged.connect(
self.table_index.v_scrollbar.setValue
)
self.table_columns.h_scrollbar.valueChanged.connect(
self.table_data.h_scrollbar.setValue
)
self.table_index.v_scrollbar.valueChanged.connect(
self.table_data.v_scrollbar.setValue
)
# Disable scrolling on the headers. Even when hidden, dragging desyncs them
self.table_index.h_scrollbar.valueChanged.connect(lambda: None)
# Add items to layout
# SpacerItem | Table_columns
# table index | TrackingSpacer
# Table Index | Table Data | V Scrollbar
# | Tracking Spacer |H Scrollbar
self._top_spacer = TrackingSpacer(ref_y=self.table_index.h_header)
self._bottom_spacer = TrackingSpacer(ref_x=self.table_columns.v_header)
self.layout_grid[0, 0] = widgets.SpacerItem(0, 0, "expanding", "expanding")
self.layout_grid[0, 1:2] = self.table_columns
self.layout_grid[1:2, 0:1] = self.table_index
self.layout_grid[1, 2] = self._top_spacer
self.layout_grid[2, 2] = self.table_data
self.layout_grid[2, 3] = self.table_data.v_scrollbar
self.layout_grid[3, 1] = self._bottom_spacer
self.layout_grid[3, 2] = self.table_data.h_scrollbar
# The data table takes all extra space, so the viewer fills its parent
# (a small frame leaves empty table area instead of a shrunken widget).
self.layout_grid.setColumnStretch(2, 1)
self.layout_grid.setRowStretch(2, 1)
# Headers keep their content size: pin them to the data table's edges.
self.layout_grid.setAlignment(self.table_columns, constants.ALIGN_LEFT)
self.layout_grid.setAlignment(self.table_index, constants.ALIGN_TOP)
self._apply_style()
# Connected after the models were created, so they are reset before
# the header layout gets rebuilt.
self.holder.changed.connect(self._on_df_changed)
self.holder.row_order_changed.connect(self._on_row_order_changed)
self._on_df_changed()
def _apply_style(self):
"""Derive the colours from the viewer's palette (light or dark theme)."""
colors = _viewer_style.ViewerColors.from_palette(self.palette())
self._colors = colors
_viewer_style.style_table(self.table_data, colors.base, colors.alt_row)
_viewer_style.style_table(self.table_columns, colors.header_bg)
_viewer_style.style_table(self.table_index, colors.header_bg)
level_names = _viewer_style.level_name_header_style(colors)
self.table_columns.v_header.setStyleSheet(level_names)
self.table_index.h_header.setStyleSheet(level_names)
for view in (self.table_data, self.table_columns, self.table_index):
_viewer_style.restyle_view(view, colors)
self._top_spacer.set_colors(colors.header_outer_bg, colors.divider)
self._bottom_spacer.set_colors(colors.header_outer_bg)
self.update()
def paintEvent(self, event: gui.QPaintEvent):
_viewer_style.paint_frame(self, self._colors)
def changeEvent(self, event: core.QEvent):
super().changeEvent(event)
if event.type() in {
core.QEvent.Type.PaletteChange,
core.QEvent.Type.StyleChange, # e.g. an application style sheet (theme)
}:
self._apply_style() # sets the children's palettes only: no recursion
@property
def df(self) -> Any:
return self.holder.df
@df.setter
def df(self, df: Any):
self.set_df(df)
def set_df(self, df: Any):
"""Show another frame (in every model / widget sharing the holder)."""
self.holder.df = df
def _on_row_order_changed(self, origin=None):
# Spans group adjacent equal labels: only meaningful in the frame's order.
self.table_index.refresh(set_spans=self.holder.row_order is None)
def _on_df_changed(self, origin=None):
"""Rebuild header spans and sizes for the holder's current frame."""
df = self.df
self._autosized_cols.clear()
self.table_columns.refresh()
self.table_index.refresh()
# Only show the level-name headers if there are level names
v_header = self.table_columns.v_header
h_header = self.table_index.h_header
if _has_level_names(df, horizontal=True):
v_header.setMinimumWidth(0)
v_header.setMaximumWidth(QWIDGETSIZE_MAX)
else:
v_header.setFixedWidth(0)
if _has_level_names(df, horizontal=False):
h_header.setMinimumHeight(0)
h_header.setMaximumHeight(QWIDGETSIZE_MAX)
else:
h_header.setFixedHeight(0)
self._resize_columns()
self.table_data.updateGeometry()
self.table_columns.updateGeometry()
self.table_index.updateGeometry() # its width follows the index labels
def jump_to_column(self, col_num: int):
"""Make sure column at given index is visible.
Scrolls to column at given index.
Arguments:
col_num: column to scroll to
"""
if (model := self.table_data.model()) is not None:
idx = model.index(0, col_num)
self.table_data.scrollTo(idx)
if (model := self.table_index.model()) is not None:
idx = model.index(0, col_num)
self.table_index.scrollTo(idx)
if (model := self.table_columns.model()) is not None:
idx = model.index(0, col_num)
self.table_columns.scrollTo(idx)
# def on_column_selection_changed(self, selected, deselected):
# if self.table_columns.hasFocus():
# selected = self.table_columns.get_higher_levels()
# self.table_data.selectionModel().select(
# selected,
# SelectionFlag.Columns
# | SelectionFlag.ClearAndSelect,
# )
# self.table_columns._on_selection_changed(selected, deselected)
# def on_index_selection_changed(self, selected, deselected):
# if not self.table_index.hasFocus():
# return
# selected = self.table_index.get_higher_levels()
# self.table_data.selectionModel().select(
# selected,
# SelectionFlag.Rows
# | SelectionFlag.ClearAndSelect,
# )
# self.table_index._on_selection_changed(selected, deselected)
def on_clicked(self, ix: core.QModelIndex):
"""Request a sort by the clicked leaf column; clicking again reverses."""
col_model = self.table_columns.model()
if not ix.isValid() or col_model is None:
return
if ix.row() == col_model.rowCount() - 1:
self.sorter.request_sort(ix.column())
def showEvent(self, event: gui.QShowEvent):
"""Initialize column and row sizes on the first time the widget is shown."""
if not self._loaded and self.df is not None:
# Set column widths
self._resize_columns()
self._loaded = True
event.accept()
def _resize_columns(self):
"""Fit the first columns to header + first rows; one single-line row height."""
columns = min(
self.table_data.model().columnCount(), _viewer_style.AUTOSIZE_COLUMNS
)
for column_index in range(columns):
self.auto_size_column(column_index)
# Cells do not wrap, so a row is one line of text.
height = min(self.table_data.fontMetrics().height() + ROW_PADDING, MAX_ROW_HEIGHT)
self.table_index.v_header.setDefaultSectionSize(height)
self.table_data.v_header.setDefaultSectionSize(height)
def _autosize_visible_columns(self, _value: int = 0):
"""Lazily auto-size wide-frame columns as they scroll into view."""
model = self.table_data.model()
if model is None:
return
col_count = model.columnCount()
if len(self._autosized_cols) >= col_count:
return
vp_width = self.table_data.viewport().width()
first = self.table_data.columnAt(0)
if first < 0:
return
last = self.table_data.columnAt(max(0, vp_width - 1))
end = col_count if last < 0 else min(col_count, last + 1)
for col in range(first, end):
if col not in self._autosized_cols:
self.auto_size_column(col)
def on_column_selection_changed(self, selected, deselected):
if not self.table_columns.hasFocus():
return
higher_levels = self.table_columns.get_higher_levels()
# Set selection mode so selecting one row or column at a time
# adds to selection each time
selected.merge(higher_levels, SelectionFlag.Deselect)
# Select the cells in the data view
self.table_data.selectionModel().select(
selected, SelectionFlag.Columns | SelectionFlag.ClearAndSelect
)
def on_index_selection_changed(self, selected, deselected):
if not self.table_index.hasFocus():
return
higher_levels = self.table_index.get_higher_levels()
selected.merge(higher_levels, SelectionFlag.Deselect)
self.table_data.selectionModel().select(
selected, SelectionFlag.Rows | SelectionFlag.ClearAndSelect
)
def _on_selection_changed(self, selected, deselected):
"""Runs when cells are selected in the main table.
This logic highlights the correct
cells in the vertical and horizontal headers when a data cell is selected
"""
# The two blocks below check what columns or rows are selected in the data table
# and highlights thecorresponding ones in the two headers. The if statements
# check for focus on headers, because if the user clicks a header that will
# auto-select all cells in that row or column which will trigger this function
# and cause and infinite loop
if not self.table_columns.hasFocus():
self.table_columns.selectionModel().select(
selected, SelectionFlag.Columns | SelectionFlag.ClearAndSelect
)
if not self.table_index.hasFocus():
self.table_index.selectionModel().select(
selected, SelectionFlag.Rows | SelectionFlag.ClearAndSelect
)
def auto_size_column(self, column_index: int):
"""Set the size of column at column_index to fit its contents."""
self._autosized_cols.add(column_index)
col_model = self.table_columns.model()
data_model = self.table_data.model()
if col_model is None or data_model is None:
return
rows = range(min(data_model.rowCount(), _viewer_style.SAMPLE_ROWS))
width = _viewer_style.fitted_column_width(
(
str(col_model.data(col_model.index(r, column_index)) or "")
for r in range(col_model.rowCount())
),
self.table_columns.font(),
(str(data_model.data(data_model.index(r, column_index)) or "") for r in rows),
self.table_data.fontMetrics(),
icon_space=_viewer_style.HEADER_ICON_SPACE if self._dtype_icons else 0,
)
self.table_columns.setColumnWidth(column_index, width)
self.table_data.setColumnWidth(column_index, width)
self.table_data.updateGeometry()
self.table_columns.updateGeometry()
def auto_size_row(self, row_index: int):
"""Set the size of row at row_index to fix its contents."""
padding = 20
self.table_index.resizeRowToContents(row_index)
height = self.table_index.rowHeight(row_index)
# Iterate over the row's columns and check the width of each to
# determine the max height for the row
# Only check the first columns for performance.
max_columns = 100
model = self.table_data.model()
for i in range(min(max_columns, model.columnCount())):
mi = model.index(row_index, i)
cell_width = self.table_columns.columnWidth(i)
text = model.data(mi)
# Gets row height at a constrained width (the column width).
# This constrained width, with the flag of Qt.TextWordWrap
# gets the height the cell would have to be to fit the text.
constrained_rect = core.Rect(0, 0, cell_width, 0)
text = str(text) # TODO: remove this?
h = (
self.table_data
.fontMetrics()
.boundingRect(constrained_rect, constants.TextFlag.TextWordWrap, text)
.height()
)
height = max(height, h)
height += padding
self.table_index.setRowHeight(row_index, height)
self.table_data.setRowHeight(row_index, height)
self.table_data.updateGeometry()
self.table_index.updateGeometry()
def data_changed(self):
# Call dataChanged on all models for all data
for model in [
self.table_data.model(),
self.table_columns.model(),
self.table_index.model(),
]:
model.update_all()