Skip to content

HeaderView

Base classes

Name Children Inherits
OrientedTableView
prettyqt.custom_widgets.orientedtableview
TableView class with some convenience methods for oriented tables.

â‹” Inheritance diagram

graph TD
  4163280918["dataframeviewer.HeaderView"]
  682009552["custom_widgets.OrientedTableView"]
  1288268085["widgets.TableView"]
  2313507980["widgets.TableViewMixin"]
  3836649406["widgets.AbstractItemViewMixin"]
  1259044718["widgets.AbstractScrollAreaMixin"]
  1689631995["widgets.FrameMixin"]
  829357528["widgets.WidgetMixin"]
  3227531497["core.ObjectMixin"]
  2751680898["builtins.object"]
  625385617["gui.PaintDeviceMixin"]
  2105279592["QtWidgets.QTableView"]
  2555450592["QtWidgets.QAbstractItemView"]
  2048140712["QtWidgets.QAbstractScrollArea"]
  1267405807["QtWidgets.QFrame"]
  1348938779["QtWidgets.QWidget"]
  13951691["QtCore.QObject"]
  395147830["sip.wrapper"]
  46922758["sip.simplewrapper"]
  2007623938["QtGui.QPaintDevice"]
  682009552 --> 4163280918
  1288268085 --> 682009552
  2313507980 --> 1288268085
  3836649406 --> 2313507980
  1259044718 --> 3836649406
  1689631995 --> 1259044718
  829357528 --> 1689631995
  3227531497 --> 829357528
  2751680898 --> 3227531497
  625385617 --> 829357528
  2751680898 --> 625385617
  2105279592 --> 1288268085
  2555450592 --> 2105279592
  2048140712 --> 2555450592
  1267405807 --> 2048140712
  1348938779 --> 1267405807
  13951691 --> 1348938779
  395147830 --> 13951691
  46922758 --> 395147830
  2751680898 --> 46922758
  2007623938 --> 1348938779
  46922758 --> 2007623938

🛈 DocStrings

Bases: OrientedTableView

Displays the DataFrame index or columns depending on orientation.

Source code in src/cutepandas/pandaswidgets/dataframeviewer.py
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)

init_size

init_size()

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).

Source code in src/cutepandas/pandaswidgets/dataframeviewer.py
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))

refresh

refresh(set_spans: bool = True)

Rebuild spans and sizes after the frame changed.

Source code in src/cutepandas/pandaswidgets/dataframeviewer.py
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())

set_spans

set_spans()

Merge adjacent equal header labels into one spanning cell per level.

Source code in src/cutepandas/pandaswidgets/dataframeviewer.py
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)

:fa-brands-github: Show source on GitHub