Skip to content

GridDataFrameViewer

Base classes

Name Children Inherits
SortableViewerMixin
cutepandas.pandaswidgets.sortcontroller
Viewer sort API delegating to `self.sorter` (a `SortController`).
Widget
prettyqt.widgets.widget
The base class of all user interface objects.

â‹” Inheritance diagram

graph TD
  2729611392["gridviewer.GridDataFrameViewer"]
  1636368185["sortcontroller.SortableViewerMixin"]
  2751680898["builtins.object"]
  3664736470["widgets.Widget"]
  829357528["widgets.WidgetMixin"]
  3227531497["core.ObjectMixin"]
  625385617["gui.PaintDeviceMixin"]
  1348938779["QtWidgets.QWidget"]
  13951691["QtCore.QObject"]
  395147830["sip.wrapper"]
  46922758["sip.simplewrapper"]
  2007623938["QtGui.QPaintDevice"]
  1636368185 --> 2729611392
  2751680898 --> 1636368185
  3664736470 --> 2729611392
  829357528 --> 3664736470
  3227531497 --> 829357528
  2751680898 --> 3227531497
  625385617 --> 829357528
  2751680898 --> 625385617
  1348938779 --> 3664736470
  13951691 --> 1348938779
  395147830 --> 13951691
  46922758 --> 395147830
  2751680898 --> 46922758
  2007623938 --> 1348938779
  46922758 --> 2007623938

🛈 DocStrings

Bases: SortableViewerMixin, Widget

Four-table 2x2 grid viewer with flush corner, column header, index, and data.

Layout

table_level | table_header | (corner) table_index | table_data | vscroll | hscroll |

Because table_level occupies the top-left quadrant with the exact height of table_header and exact width of table_index, headers sit completely flush against table_data with no spacer gaps — even when both row and column MultiIndexes have level names.

Source code in src/cutepandas/pandaswidgets/gridviewer.py
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
class GridDataFrameViewer(SortableViewerMixin, widgets.Widget):
    """Four-table 2x2 grid viewer with flush corner, column header, index, and data.

    Layout:
        table_level  | table_header | (corner)
        table_index  | table_data   | vscroll
                     | hscroll      |

    Because `table_level` occupies the top-left quadrant with the exact height of
    `table_header` and exact width of `table_index`, headers sit completely flush
    against `table_data` with no spacer gaps — even when both row and column
    MultiIndexes have level names.
    """

    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,
        parent: widgets.QWidget | None = None,
        **kwargs,
    ) -> None:
        super().__init__(parent=parent, **kwargs)
        if not self.objectName():
            self.setObjectName("cutepandas_grid_dataframe_viewer")
        self._dtype_icons = dtype_icons
        self._syncing_selection = False
        self._autosized_cols: set[int] = set()
        self._resizing_col: int | None = None
        self._resize_start_x = 0
        self._resize_initial_w = 0
        self._resizing_row: int | None = None
        self._resize_start_y = 0
        self._resize_initial_h = 0

        if isinstance(df, DataFrameHolder):
            self.holder = df
        else:
            self.holder = DataFrameHolder(df, parent=self)

        self.set_size_policy("expanding", "expanding")

        # 1. Data table (bottom-right)
        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()

        # 2. Corner level table (top-left)
        self.table_level = widgets.TableView(parent=self)
        self.table_level.h_header.hide()
        self.table_level.v_header.hide()
        self.table_level.set_edit_triggers("none")
        self.table_level.set_scrollbar_policy("always_off")
        self.table_level.setSelectionMode(
            widgets.QAbstractItemView.SelectionMode.NoSelection
        )
        self.table_level.setFocusPolicy(constants.FocusPolicy.NoFocus)
        self.table_level.setWordWrap(False)
        self.table_level.setItemDelegate(
            _viewer_style.CornerCellDelegate(self.table_level)
        )
        self.table_level.set_model(CornerLevelModel(self.holder, parent=self.table_level))

        # 3. Column header table (top-right)
        self.table_header = widgets.TableView(parent=self)
        self.table_header.h_header.hide()
        self.table_header.v_header.hide()
        self.table_header.set_edit_triggers("none")
        self.table_header.set_scrollbar_policy("always_off")
        self.table_header.set_scroll_mode("pixel")
        self.table_header.setWordWrap(False)
        self.table_header.setMouseTracking(True)
        self.table_header.viewport().setMouseTracking(True)
        self.table_header.viewport().installEventFilter(self)

        def _kind_for_col(col: int):
            cols = self.table_data.get_model(skip_proxies=True).column_info
            return cols[col].kind if 0 <= col < len(cols) else None

        self.table_header.setItemDelegate(
            _viewer_style.HeaderCellDelegate(
                constants.HORIZONTAL,
                self.table_header,
                sort_state_getter=self.get_sort_state,
                kind_getter=_kind_for_col,
                show_dtype_icons=dtype_icons,
            )
        )
        self.table_header.set_model(
            pandasmodels.HorizontalHeaderModel(self.holder, parent=self.table_header)
        )
        self.table_header.clicked.connect(self._on_header_clicked)
        self.sorter.sort_state_changed.connect(
            lambda _state: self.table_header.viewport().update()
        )

        # 4. Row index table (bottom-left)
        self.table_index = widgets.TableView(parent=self)
        self.table_index.h_header.hide()
        self.table_index.v_header.hide()
        self.table_index.set_edit_triggers("none")
        self.table_index.set_scrollbar_policy("always_off")
        self.table_index.set_scroll_mode("pixel")
        self.table_index.setWordWrap(False)
        self.table_index.setMouseTracking(True)
        self.table_index.viewport().setMouseTracking(True)
        self.table_index.viewport().installEventFilter(self)
        self.table_index.setItemDelegate(
            _viewer_style.HeaderCellDelegate(constants.VERTICAL, self.table_index)
        )
        self.table_index.set_model(
            pandasmodels.VerticalHeaderModel(self.holder, parent=self.table_index)
        )

        # Link scrollbars
        self.table_data.h_scrollbar.valueChanged.connect(
            self.table_header.h_scrollbar.setValue
        )
        self.table_data.h_scrollbar.valueChanged.connect(self._autosize_visible_columns)
        self.table_header.h_scrollbar.valueChanged.connect(
            self.table_data.h_scrollbar.setValue
        )
        self.table_data.v_scrollbar.valueChanged.connect(
            self.table_index.v_scrollbar.setValue
        )
        self.table_index.v_scrollbar.valueChanged.connect(
            self.table_data.v_scrollbar.setValue
        )

        # Link selections
        self.table_data.selectionModel().selectionChanged.connect(
            self._on_data_selection_changed
        )
        self.table_header.selectionModel().selectionChanged.connect(
            self._on_header_selection_changed
        )
        self.table_index.selectionModel().selectionChanged.connect(
            self._on_index_selection_changed
        )

        # 2x2 grid layout + scrollbars
        layout = self.set_layout("grid", spacing=0, margin=0)
        # room for the 1 px outer border painted by paintEvent
        layout.setContentsMargins(1, 1, 1, 1)
        layout[0, 0] = self.table_level
        layout[0, 1] = self.table_header
        layout[1, 0] = self.table_index
        layout[1, 1] = self.table_data
        layout[1, 2] = self.table_data.v_scrollbar
        layout[2, 1] = self.table_data.h_scrollbar
        layout.setColumnStretch(1, 1)
        layout.setRowStretch(1, 1)

        self.setFocusProxy(self.table_data)
        self._apply_style()

        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_header, colors.header_bg)
        _viewer_style.style_table(self.table_index, colors.header_bg)
        _viewer_style.style_table(self.table_level, colors.header_outer_bg)
        for view in (
            self.table_data,
            self.table_header,
            self.table_index,
            self.table_level,
        ):
            _viewer_style.restyle_view(view, colors)
        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: Any = None):
        # Spans group adjacent equal labels: only meaningful in the frame's order.
        if self.holder.row_order is None:
            _apply_axis_spans(self.table_index, self.df, horizontal=False)
        else:
            self.table_index.clearSpans()

    def _on_df_changed(self, origin: Any = None):
        self._autosized_cols.clear()
        _apply_axis_spans(self.table_header, self.df, horizontal=True)
        _apply_axis_spans(self.table_index, self.df, horizontal=False)
        self._resize_all()
        self.table_header.viewport().update()

    def jump_to_column(self, col_num: int):
        """Scroll horizontally so `col_num` is visible."""
        if (model := self.table_data.model()) is not None:
            idx = model.index(0, col_num)
            self.table_data.scrollTo(idx)
        if (model := self.table_header.model()) is not None:
            idx = model.index(0, col_num)
            self.table_header.scrollTo(idx)
        self._autosize_visible_columns()

    def _resize_all(self):
        data_model = self.table_data.model()
        header_model = self.table_header.model()
        index_model = self.table_index.model()
        level_model = self.table_level.model()
        if (
            data_model is None
            or header_model is None
            or index_model is None
            or level_model is None
        ):
            return

        # 1. Row height for data + index
        row_h = min(self.table_data.fontMetrics().height() + ROW_PADDING, MAX_ROW_HEIGHT)
        self.table_data.v_header.setDefaultSectionSize(row_h)
        self.table_index.v_header.setDefaultSectionSize(row_h)

        # 2. Header row height (for table_header & table_level)
        hdr_row_h = self.table_header.fontMetrics().height() + HEADER_ROW_PADDING
        self.table_header.v_header.setDefaultSectionSize(hdr_row_h)
        self.table_level.v_header.setDefaultSectionSize(hdr_row_h)

        # 3. Fit data / header columns
        for col in range(min(data_model.columnCount(), _viewer_style.AUTOSIZE_COLUMNS)):
            self.auto_size_column(col)

        # 4. Fit index / corner columns (bounded sample + last row for trailing width)
        metrics = self.table_index.fontMetrics()
        rows = _viewer_style.sample_rows(index_model.rowCount())
        idx_total_w = 0
        for col in range(index_model.columnCount()):
            texts = [
                str(level_model.data(level_model.index(r, col)) or "")
                for r in range(level_model.rowCount())
            ]
            texts.extend(
                str(index_model.data(index_model.index(r, col)) or "") for r in rows
            )
            w = _viewer_style.fitted_index_width(texts, metrics)
            self.table_index.setColumnWidth(col, w)
            # Qt may round up to its minimum section size: use the applied width.
            w = self.table_index.columnWidth(col)
            self.table_level.setColumnWidth(col, w)
            idx_total_w += w

        hdr_total_h = header_model.rowCount() * hdr_row_h

        self.table_header.setFixedHeight(hdr_total_h)
        self.table_level.setFixedHeight(hdr_total_h)
        self.table_index.setFixedWidth(idx_total_w)
        self.table_level.setFixedWidth(idx_total_w)

    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 auto_size_column(self, column_index: int):
        """Fit `column_index` in both `table_header` and `table_data`."""
        self._autosized_cols.add(column_index)
        data_model = self.table_data.model()
        header_model = self.table_header.model()
        if (
            data_model is None
            or header_model is None
            or not 0 <= column_index < data_model.columnCount()
        ):
            return
        rows = range(min(data_model.rowCount(), _viewer_style.SAMPLE_ROWS))
        width = _viewer_style.fitted_column_width(
            (
                str(header_model.data(header_model.index(r, column_index)) or "")
                for r in range(header_model.rowCount())
            ),
            self.table_header.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_header.setColumnWidth(column_index, width)
        self.table_data.setColumnWidth(column_index, width)

    # --- interactive header column resizing ---

    def _header_edge_at(self, x: int) -> int | None:
        header_x = x + self.table_header.h_scrollbar.value()
        col = self.table_header.columnAt(x)
        if col < 0:
            return None
        right_edge = self.table_header.columnViewportPosition(
            col
        ) + self.table_header.columnWidth(col)
        if abs(x - right_edge) <= EDGE_TOLERANCE:
            return col
        left_edge = self.table_header.columnViewportPosition(col)
        if col > 0 and abs(x - left_edge) <= EDGE_TOLERANCE and header_x >= 0:
            return col - 1
        return None

    def _index_edge_at(self, y: int) -> int | None:
        row = self.table_index.rowAt(y)
        if row < 0:
            return None
        bottom_edge = self.table_index.rowViewportPosition(
            row
        ) + self.table_index.rowHeight(row)
        if abs(y - bottom_edge) <= EDGE_TOLERANCE:
            return row
        top_edge = self.table_index.rowViewportPosition(row)
        if row > 0 and abs(y - top_edge) <= EDGE_TOLERANCE:
            return row - 1
        return None

    def eventFilter(self, watched: core.QObject, event: core.QEvent) -> bool:
        if watched is self.table_header.viewport() and isinstance(event, gui.QMouseEvent):
            x = int(event.position().x())
            match event.type():
                case core.QEvent.Type.MouseButtonPress:
                    col = self._header_edge_at(x)
                    if col is not None:
                        self._resizing_col = col
                        self._resize_start_x = x
                        self._resize_initial_w = self.table_header.columnWidth(col)
                        return True
                case core.QEvent.Type.MouseButtonRelease:
                    if self._resizing_col is not None:
                        self._resizing_col = None
                        return True
                case core.QEvent.Type.MouseButtonDblClick:
                    col = self._header_edge_at(x)
                    if col is not None:
                        self.auto_size_column(col)
                        return True
                case core.QEvent.Type.MouseMove:
                    if self._resizing_col is not None:
                        new_w = max(
                            MIN_DRAG_COLUMN_WIDTH,
                            self._resize_initial_w + x - self._resize_start_x,
                        )
                        self.table_header.setColumnWidth(self._resizing_col, new_w)
                        self.table_data.setColumnWidth(self._resizing_col, new_w)
                        return True
                    cursor = (
                        constants.CursorShape.SplitHCursor
                        if self._header_edge_at(x) is not None
                        else constants.CursorShape.ArrowCursor
                    )
                    self.table_header.viewport().setCursor(gui.Cursor(cursor))
        elif watched is self.table_index.viewport() and isinstance(
            event, gui.QMouseEvent
        ):
            y = int(event.position().y())
            match event.type():
                case core.QEvent.Type.MouseButtonPress:
                    row = self._index_edge_at(y)
                    if row is not None:
                        self._resizing_row = row
                        self._resize_start_y = y
                        self._resize_initial_h = self.table_index.rowHeight(row)
                        return True
                case core.QEvent.Type.MouseButtonRelease:
                    if self._resizing_row is not None:
                        self._resizing_row = None
                        return True
                case core.QEvent.Type.MouseMove:
                    if self._resizing_row is not None:
                        new_h = max(
                            MIN_DRAG_ROW_HEIGHT,
                            self._resize_initial_h + y - self._resize_start_y,
                        )
                        self.table_index.setRowHeight(self._resizing_row, new_h)
                        self.table_data.setRowHeight(self._resizing_row, new_h)
                        return True
                    cursor = (
                        constants.CursorShape.SplitVCursor
                        if self._index_edge_at(y) is not None
                        else constants.CursorShape.ArrowCursor
                    )
                    self.table_index.viewport().setCursor(gui.Cursor(cursor))
        return super().eventFilter(watched, event)

    # --- selection syncing ---

    def _on_data_selection_changed(self, selected, deselected):
        if self._syncing_selection:
            return
        self._syncing_selection = True
        try:
            self.table_header.selectionModel().select(
                selected, SelectionFlag.Columns | SelectionFlag.ClearAndSelect
            )
            self.table_index.selectionModel().select(
                selected, SelectionFlag.Rows | SelectionFlag.ClearAndSelect
            )
        finally:
            self._syncing_selection = False

    def _on_header_selection_changed(self, selected, deselected):
        if self._syncing_selection or not self.table_header.hasFocus():
            return
        self._syncing_selection = True
        try:
            self.table_data.selectionModel().select(
                selected, SelectionFlag.Columns | SelectionFlag.ClearAndSelect
            )
            self.table_index.selectionModel().clear()
        finally:
            self._syncing_selection = False

    def _on_index_selection_changed(self, selected, deselected):
        if self._syncing_selection or not self.table_index.hasFocus():
            return
        self._syncing_selection = True
        try:
            self.table_data.selectionModel().select(
                selected, SelectionFlag.Rows | SelectionFlag.ClearAndSelect
            )
            self.table_header.selectionModel().clear()
        finally:
            self._syncing_selection = False

    # --- sorting ---

    def _on_header_clicked(self, ix: core.QModelIndex):
        header_model = self.table_header.model()
        if not ix.isValid() or header_model is None:
            return
        if ix.row() == header_model.rowCount() - 1:
            self.sorter.request_sort(ix.column())

auto_size_column

auto_size_column(column_index: int)

Fit column_index in both table_header and table_data.

Source code in src/cutepandas/pandaswidgets/gridviewer.py
def auto_size_column(self, column_index: int):
    """Fit `column_index` in both `table_header` and `table_data`."""
    self._autosized_cols.add(column_index)
    data_model = self.table_data.model()
    header_model = self.table_header.model()
    if (
        data_model is None
        or header_model is None
        or not 0 <= column_index < data_model.columnCount()
    ):
        return
    rows = range(min(data_model.rowCount(), _viewer_style.SAMPLE_ROWS))
    width = _viewer_style.fitted_column_width(
        (
            str(header_model.data(header_model.index(r, column_index)) or "")
            for r in range(header_model.rowCount())
        ),
        self.table_header.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_header.setColumnWidth(column_index, width)
    self.table_data.setColumnWidth(column_index, width)

jump_to_column

jump_to_column(col_num: int)

Scroll horizontally so col_num is visible.

Source code in src/cutepandas/pandaswidgets/gridviewer.py
def jump_to_column(self, col_num: int):
    """Scroll horizontally so `col_num` is visible."""
    if (model := self.table_data.model()) is not None:
        idx = model.index(0, col_num)
        self.table_data.scrollTo(idx)
    if (model := self.table_header.model()) is not None:
        idx = model.index(0, col_num)
        self.table_header.scrollTo(idx)
    self._autosize_visible_columns()

set_df

set_df(df: Any)

Show another frame (in every model / widget sharing the holder).

Source code in src/cutepandas/pandaswidgets/gridviewer.py
def set_df(self, df: Any):
    """Show another frame (in every model / widget sharing the holder)."""
    self.holder.df = df

:fa-brands-github: Show source on GitHub