class HeaderView(custom_widgets.OrientedTableView):
"""Displays the DataFrame index or columns depending on orientation."""
def __init__(
self,
parent: DataFrameViewer,
orientation: constants.Orientation,
*,
show_dtype_icons: bool = False,
):
super().__init__(orientation, parent=parent)
self.table = parent.table_data
# These are used during column resizing
self._header_is_resizing = None
self.resize_start_pos: int | None = None
self.initial_header_size = None
# Handled by self.eventFilter()
self.setMouseTracking(True)
self.viewport().setMouseTracking(True)
self.viewport().installEventFilter(self)
# Settings
self.set_size_policy("maximum", "maximum")
self.setWordWrap(False)
self.set_horizontal_scrollbar_policy("always_off")
self.set_scroll_mode("pixel")
self.set_margin(0)
def _kind_for_col(col: int):
cols = self.table.get_model(skip_proxies=True).column_info
return cols[col].kind if 0 <= col < len(cols) else None
self.setItemDelegate(
_viewer_style.HeaderCellDelegate(
orientation,
self,
sort_state_getter=parent.get_sort_state if self.is_horizontal() else None,
kind_getter=_kind_for_col if self.is_horizontal() else None,
show_dtype_icons=show_dtype_icons and self.is_horizontal(),
)
)
# Orientation specific settings
if self.is_horizontal():
self.set_horizontal_scrollbar_policy("always_off")
self.h_header.hide()
self.v_header.setSectionsClickable(False)
# Selection lags without this
self.v_header.setHighlightSections(False)
else:
self.set_vertical_scrollbar_policy("always_off")
self.v_header.hide()
self.h_header.setSectionsClickable(False)
self.h_header.setHighlightSections(False)
if self.is_horizontal():
model = pandasmodels.HorizontalHeaderModel(parent.holder, parent=self)
else:
model = pandasmodels.VerticalHeaderModel(parent.holder, parent=self)
self.set_model(model)
def refresh(self, set_spans: bool = True):
"""Rebuild spans and sizes after the frame changed."""
self.clearSpans() # spans of a previous frame
if set_spans and self.get_model(skip_proxies=True).df is not None:
self.set_spans()
self.init_size()
# Set initial size
self.resize(self.sizeHint())
def get_higher_levels(self, levels: int | None = None) -> core.ItemSelection:
model = self.model()
if self.is_horizontal():
# Get the header's selected columns
# Removes the higher levels so that only the lowest level of the header
# affects the data table selection
last_row_ix = _nlevels(model.df, horizontal=True) - 1
last_col_ix = model.columnCount() - 1
return core.ItemSelection(
model.index(0, 0), model.index(last_row_ix - 1, last_col_ix)
)
last_row_ix = model.rowCount() - 1
last_col_ix = _nlevels(model.df, horizontal=False) - 1
return core.ItemSelection(
model.index(0, 0), model.index(last_row_ix, last_col_ix - 1)
)
# Take the current set of selected cells and make it so that any spanning cell above
# a selected cell is selected too This should happen after every selection change
def selectionChanged(self, selected, deselected):
super().selectionChanged(selected, deselected) # repaints the selection
df = self.get_model(skip_proxies=True).df
if df is None:
return
if self.is_horizontal():
if _nlevels(df, horizontal=True) == 1:
return
for ix in self.selectedIndexes():
for row in range(ix.row()):
ix2 = self.model().index(row, ix.column())
self.setSelection(self.visualRect(ix2), SelectionFlag.Select)
else:
if _nlevels(df, horizontal=False) == 1:
return
for ix in self.selectedIndexes():
for col in range(ix.column()):
ix2 = self.model().index(ix.row(), col)
self.setSelection(self.visualRect(ix2), SelectionFlag.Select)
def init_size(self):
"""Fit the index level columns (bounded row sample: O(1) in the length).
The column header's widths follow the data columns (`auto_size_column`).
"""
model = self.model()
if model is None or self.is_horizontal():
return
metrics = self.fontMetrics()
rows = _viewer_style.sample_rows(model.rowCount())
for col in range(model.columnCount()):
name = model.headerData(col, constants.HORIZONTAL, constants.DISPLAY_ROLE)
texts = [str(name or "")]
texts.extend(str(model.data(model.index(r, col)) or "") for r in rows)
self.setColumnWidth(col, _viewer_style.fitted_index_width(texts, metrics))
def set_spans(self):
"""Merge adjacent equal header labels into one spanning cell per level."""
df = self.get_model(skip_proxies=True).df
for level, start, length in axis_spans(df, self.is_horizontal()):
self.set_section_span(level, start, length)
def eventFilter(self, source: core.QObject, event: core.QEvent):
if not isinstance(event, gui.QMouseEvent):
return False
mouse_pos = event.position().x() if self.is_horizontal() else event.position().y()
mouse_pos = int(mouse_pos)
# If mouse is on an edge, start the drag resize process
match event.type():
case core.QEvent.Type.MouseButtonPress:
if self.over_header_edge(mouse_pos) is not None:
self._header_is_resizing = self.over_header_edge(mouse_pos)
self.resize_start_pos = mouse_pos
self.initial_header_size = self.sectionWidth(self._header_is_resizing)
return True
self._header_is_resizing = None
# End the drag process
case core.QEvent.Type.MouseButtonRelease:
self._header_is_resizing = None
case core.QEvent.Type.MouseButtonDblClick if self.is_horizontal():
if (header_index := self.over_header_edge(mouse_pos)) is not None:
self.parent().auto_size_column(header_index)
return True
case core.QEvent.Type.MouseButtonDblClick:
if (header_index := self.over_header_edge(mouse_pos)) is not None:
self.parent().auto_size_row(header_index)
return True
case core.QEvent.Type.MouseMove:
# If this is None, there is no drag resize happening
if self._header_is_resizing is not None:
size = self.initial_header_size + mouse_pos - self.resize_start_pos
if size > MIN_SECTION_RESIZE:
table_data = self.parent().table_data
self.setSectionWidth(self._header_is_resizing, size)
if self.is_horizontal():
table_data.setColumnWidth(self._header_is_resizing, size)
else:
table_data.setRowHeight(self._header_is_resizing, size)
self.updateGeometry()
table_data.updateGeometry()
return True
# Set the cursor shape
if self.over_header_edge(mouse_pos) is not None:
self.viewport().setCursor(self.get_split_cursor())
else:
cursor = gui.Cursor(constants.CursorShape.ArrowCursor)
self.viewport().setCursor(cursor)
return False
# Return the size of the header needed to match the corresponding DataTableView
def sizeHint(self):
if self.model() is None:
return core.Size(0, 0)
# Horizontal HeaderView
if self.is_horizontal():
# Width of DataTableView
width = self.table.sizeHint().width() + self.v_header.width()
height = 2 * self.frameWidth()
max_rows = min(100, self.model().rowCount())
for i in range(max_rows):
height += self.rowHeight(i)
# Vertical HeaderView
else:
# Height of DataTableView
height = self.table.sizeHint().height() + self.h_header.height()
width = 2 * self.frameWidth()
max_cols = min(100, self.model().columnCount())
for i in range(max_cols):
width += self.columnWidth(i)
return core.Size(width, height)
# This is needed because otherwise when the horizontal header is a single row
# it will add whitespace to be bigger
def minimumSizeHint(self):
if self.is_horizontal():
return core.Size(0, self.sizeHint().height())
return core.Size(self.sizeHint().width(), 0)