Skip to content

pandaswidgets

Class info

Classes

Name Children Inherits
CornerCellDelegate
cutepandas.pandaswidgets._viewer_style
Renderer for the top-left level-name corner table of the grid viewer.
    DataCellDelegate
    cutepandas.pandaswidgets._viewer_style
    Clean cell renderer: horizontal padding, muted null marker, no dotted focus.
      HeaderCellDelegate
      cutepandas.pandaswidgets._viewer_style
      Renderer for the multi-level column and row header tables.
        ViewerColors
        cutepandas.pandaswidgets._viewer_style
        Cohesive color tokens derived from a QPalette (works in light & dark themes).

          Re-exported classes

          Class Module Description
          ColumnProfileWidget cutepandas.pandaswidgets.columnprofilewidget Basic statistics and the most frequent values of one column of any frame.
          DataFrameListWidget cutepandas.pandaswidgets.dataframelistwidget
          DataFrameManagerWidget cutepandas.pandaswidgets.dataframemanagerwidget
          DataFrameViewer cutepandas.pandaswidgets.dataframeviewer Data table with synced column / index headers (MultiIndex spans for pandas).
          DataFrameWidget cutepandas.pandaswidgets.dataframewidget Viewer plus docks: index levels, columns, categories, column profile, attrs.
          GridDataFrameViewer cutepandas.pandaswidgets.gridviewer Four-table 2x2 grid viewer with flush corner, column header, index, and data.
          SimpleDataFrameViewer cutepandas.pandaswidgets.simpledataframeviewer Lightweight single-table viewer backed by DataFrameModel.
          TopValuesModel cutepandas.pandaswidgets.columnprofilewidget Most frequent values of a column: value, count and share of all rows.

          🛈 DocStrings

          pandaswidgets module.

          Widgets for dataframes (pandas first; most also show polars and pyarrow frames).

          ColumnProfileWidget

          Bases: TranslateMixin, Widget

          Basic statistics and the most frequent values of one column of any frame.

          Shows dtype, row / null / unique counts, min / max / mean / std and the top values with a share bar.

          set_column() computes the statistics right away (FrameSource.describe, a full column scan). For large frames compute them in a worker thread and pass the result to set_stats(), which must run on the GUI thread.

          The field labels (FIELDS) and the top values header go through translate (str -> str, e.g. gettext); set_translate() / retranslate() switch the language at runtime (see cutepandas.utils.i18n).

          Source code in src/cutepandas/pandaswidgets/columnprofilewidget.py
          class ColumnProfileWidget(TranslateMixin, widgets.Widget):
              """Basic statistics and the most frequent values of one column of any frame.
          
              Shows dtype, row / null / unique counts, min / max / mean / std and the top values
              with a share bar.
          
              `set_column()` computes the statistics right away (`FrameSource.describe`, a full
              column scan). For large frames compute them in a worker thread and pass the
              result to `set_stats()`, which must run on the GUI thread.
          
              The field labels (`FIELDS`) and the top values header go through `translate`
              (`str -> str`, e.g. gettext); `set_translate()` / `retranslate()` switch the
              language at runtime (see `cutepandas.utils.i18n`).
              """
          
              FIELDS: ClassVar = (
                  N_("Rows"),
                  N_("Nulls"),
                  N_("Unique"),
                  N_("Min"),
                  N_("Max"),
                  N_("Mean"),
                  N_("Std"),
              )
          
              def __init__(
                  self,
                  df: Any = None,
                  column: Any = None,
                  *,
                  top: int = 10,
                  translate: Translate | None = None,
                  **kwargs,
              ):
                  super().__init__(**kwargs)
                  self._translate = translate
                  self.top = top
                  layout = self.set_layout("vertical", margin=4)
                  self.title = widgets.Label()
                  self.title.setTextFormat(constants.TextFormat.RichText)
                  layout.add(self.title)
                  form = widgets.FormLayout()
                  self.value_labels: dict[str, widgets.Label] = {}
                  self.field_labels: dict[str, widgets.Label] = {}
                  for name in self.FIELDS:
                      label = widgets.Label()
                      label.set_text_interaction("by_mouse")
                      self.value_labels[name] = label
                      self.field_labels[name] = widgets.Label()
                      form.addRow(self.field_labels[name], label)
                  layout.add(form)
                  self.top_table = widgets.TableView(selection_behavior="rows")
                  self.top_table.v_header.hide()
                  self.top_table.set_delegate(ValueColorDelegate(mode="bar"), column=2)
                  layout.add(self.top_table)
                  self.retranslate()
                  self.clear()
                  if df is not None and column is not None:
                      self.set_column(df, column)
          
              def retranslate(self):
                  """Re-show the labels with the current `translate` callable."""
                  for name, label in self.field_labels.items():
                      label.set_text(f"{self._tr(name)}:")
                  if isinstance(model := self.top_table.model(), TopValuesModel):
                      model.set_translate(self._translate)
          
              def clear(self):
                  self.title.set_text("")
                  for label in self.value_labels.values():
                      label.set_text("")
                  self.top_table.set_model(
                      TopValuesModel(translate=self._translate, parent=self.top_table)
                  )
          
              def set_column(self, df: Any, column: Any):
                  """Profile a column (position or label) of a frame, source or holder."""
                  source = df.source if isinstance(df, DataFrameHolder) else as_source(df)
                  if source is None:
                      self.clear()
                      return
                  pos = self._position(source, column)
                  self.set_stats(source.columns[pos], source.describe(pos, top=self.top))
          
              @staticmethod
              def _position(source: FrameSource, column: Any) -> int:
                  names = [info.name for info in source.columns]
                  if column in names:
                      return names.index(column)
                  if isinstance(column, int) and 0 <= column < len(names):
                      return column
                  msg = f"No column {column!r}"
                  raise KeyError(msg)
          
              def set_stats(self, info: ColumnInfo, stats: ColumnStats):
                  """Show precomputed statistics (GUI thread)."""
                  self.title.set_text(f"<b>{info.label}</b> &nbsp; {info.dtype}")
                  self.setWindowIcon(icons.icon_for_kind(info.kind))
                  share = f" ({stats.null_count / stats.count:.1%})" if stats.count else ""
                  values = {
                      "Rows": str(stats.count),
                      "Nulls": f"{stats.null_count}{share}",
                      "Unique": _fmt(stats.unique),
                      "Min": _fmt(stats.min),
                      "Max": _fmt(stats.max),
                      "Mean": _fmt(stats.mean),
                      "Std": _fmt(stats.std),
                  }
                  for name, text in values.items():
                      self.value_labels[name].set_text(text)
                  old = self.top_table.model()
                  self.top_table.set_model(
                      TopValuesModel(stats.top, stats.count, translate=self._translate, parent=self)
                  )
                  if old is not None:
                      old.deleteLater()
          

          retranslate

          retranslate()
          

          Re-show the labels with the current translate callable.

          Source code in src/cutepandas/pandaswidgets/columnprofilewidget.py
          def retranslate(self):
              """Re-show the labels with the current `translate` callable."""
              for name, label in self.field_labels.items():
                  label.set_text(f"{self._tr(name)}:")
              if isinstance(model := self.top_table.model(), TopValuesModel):
                  model.set_translate(self._translate)
          

          set_column

          set_column(df: Any, column: Any)
          

          Profile a column (position or label) of a frame, source or holder.

          Source code in src/cutepandas/pandaswidgets/columnprofilewidget.py
          def set_column(self, df: Any, column: Any):
              """Profile a column (position or label) of a frame, source or holder."""
              source = df.source if isinstance(df, DataFrameHolder) else as_source(df)
              if source is None:
                  self.clear()
                  return
              pos = self._position(source, column)
              self.set_stats(source.columns[pos], source.describe(pos, top=self.top))
          

          set_stats

          set_stats(info: ColumnInfo, stats: ColumnStats)
          

          Show precomputed statistics (GUI thread).

          Source code in src/cutepandas/pandaswidgets/columnprofilewidget.py
          def set_stats(self, info: ColumnInfo, stats: ColumnStats):
              """Show precomputed statistics (GUI thread)."""
              self.title.set_text(f"<b>{info.label}</b> &nbsp; {info.dtype}")
              self.setWindowIcon(icons.icon_for_kind(info.kind))
              share = f" ({stats.null_count / stats.count:.1%})" if stats.count else ""
              values = {
                  "Rows": str(stats.count),
                  "Nulls": f"{stats.null_count}{share}",
                  "Unique": _fmt(stats.unique),
                  "Min": _fmt(stats.min),
                  "Max": _fmt(stats.max),
                  "Mean": _fmt(stats.mean),
                  "Std": _fmt(stats.std),
              }
              for name, text in values.items():
                  self.value_labels[name].set_text(text)
              old = self.top_table.model()
              self.top_table.set_model(
                  TopValuesModel(stats.top, stats.count, translate=self._translate, parent=self)
              )
              if old is not None:
                  old.deleteLater()
          

          DataFrameManagerWidget

          Bases: Splitter

          Source code in src/cutepandas/pandaswidgets/dataframemanagerwidget.py
          class DataFrameManagerWidget(widgets.Splitter):
              def __init__(self, object_name: str = "pandas_df_manager", **kwargs):
                  super().__init__(object_name=object_name, **kwargs)
                  self.dataframe_list = pandaswidgets.DataFrameListWidget()
                  self.dataframe_editor = pandaswidgets.DataFrameWidget()
                  self.dataframe_list.selectionModel().currentRowChanged.connect(
                      self._on_current_change
                  )
                  self._current_row: int | None = None
                  self.dataframe_editor.holder.changed.connect(self._on_editor_df_changed)
                  self.add(self.dataframe_list)
                  widget = widgets.Widget()
                  widget.set_layout("horizontal")
                  widget.box.add(self.dataframe_editor)
                  self.add(widget)
          
              def add_df(self, df: pd.DataFrame):
                  self.dataframe_list.add_df(df)
          
              def _on_current_change(self, new, old):
                  if not new.isValid():
                      return
                  # The list model stores the frames; its columns only provide display data.
                  df = self.dataframe_list.model().items[new.row()]
                  self._current_row = None  # loading a frame is not an edit
                  self.dataframe_editor.set_df(df)
                  self._current_row = new.row()
          
              def _on_editor_df_changed(self, origin=None):
                  """Store the edited frame in the list, replacing the one it came from."""
                  if self._current_row is None:
                      return
                  model = self.dataframe_list.model()
                  index = model.index(self._current_row, 0)
                  model.setData(index, self.dataframe_editor.df, constants.USER_ROLE)
          

          DataFrameViewer

          Bases: SortableViewerMixin, 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.

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

          __init__

          __init__(
              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.

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

          auto_size_column

          auto_size_column(column_index: int)
          

          Set the size of column at column_index to fit its contents.

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

          auto_size_row

          auto_size_row(row_index: int)
          

          Set the size of row at row_index to fix its contents.

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

          jump_to_column

          jump_to_column(col_num: int)
          

          Make sure column at given index is visible.

          Scrolls to column at given index.

          Parameters:

          Name Type Description Default
          col_num int

          column to scroll to

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

          on_clicked

          on_clicked(ix: QModelIndex)
          

          Request a sort by the clicked leaf column; clicking again reverses.

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

          set_df

          set_df(df: Any)
          

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

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

          showEvent

          showEvent(event: QShowEvent)
          

          Initialize column and row sizes on the first time the widget is shown.

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

          DataFrameWidget

          Bases: TranslateMixin, MainWindow

          Viewer plus docks: index levels, columns, categories, column profile, attrs.

          Shows pandas, pyarrow and polars frames. For pandas frames the column and category lists edit the frame (rename, dtype, reorder, ...); for other backends they are read-only and the index list stays empty.

          Dock titles and the labels of the panels go through translate (str -> str); set_translate() / retranslate() switch the language at runtime.

          Source code in src/cutepandas/pandaswidgets/dataframewidget.py
          class DataFrameWidget(TranslateMixin, widgets.MainWindow):
              """Viewer plus docks: index levels, columns, categories, column profile, attrs.
          
              Shows pandas, pyarrow and polars frames. For pandas frames the column and
              category lists edit the frame (rename, dtype, reorder, ...); for other backends
              they are read-only and the index list stays empty.
          
              Dock titles and the labels of the panels go through `translate` (`str -> str`);
              `set_translate()` / `retranslate()` switch the language at runtime.
              """
          
              DOCK_TITLES = (
                  N_("Index list"),
                  N_("Column list"),
                  N_("Category list"),
                  N_("Column profile"),
                  N_("MetaData"),
              )
          
              current_index_changed = core.Signal(core.ModelIndex)  # ty: ignore[missing-argument]
              current_row_changed = core.Signal(int)  # ty: ignore[missing-argument]
          
              def __init__(
                  self,
                  df: Any = None,
                  object_name: str = "pandas_window",
                  *,
                  translate: Translate | None = None,
                  **kwargs,
              ):
                  super().__init__(object_name=object_name, **kwargs)
                  self._translate = translate
          
                  # Every panel works on this holder, so an edit in one shows up in all of them.
                  self.holder = pandasmodels.DataFrameHolder(df, parent=self)
                  self._is_pandas: bool | None = None
                  self.index_table = widgets.TableView(selection_behavior="rows")
                  self.column_table = widgets.TableView(selection_behavior="rows")
                  self.column_table.set_delegate(delegates.DTypeDelegate(), column=1)
                  self.data_table = pandaswidgets.DataFrameViewer(self.holder)
                  self.setCentralWidget(self.data_table)
                  self.category_table = widgets.TableView(selection_behavior="rows")
                  self.profile = pandaswidgets.ColumnProfileWidget(translate=translate)
                  self.attrs_table = widgets.TreeView(
                      selection_behavior="rows", root_is_decorated=False
                  )
                  panels = (
                      self.index_table,
                      self.column_table,
                      self.category_table,
                      self.profile,
                      self.attrs_table,
                  )
                  self.docks = [self.add_dockwidget(panel) for panel in panels]
                  self.holder.changed.connect(self._on_df_changed)
                  self._on_df_changed()
                  self.retranslate()
          
              def retranslate(self):
                  """Re-show dock titles and panel labels with the current `translate`."""
                  for dock, title in zip(self.docks, self.DOCK_TITLES):
                      dock.setWindowTitle(self._tr(title))
                  self.profile.set_translate(self._translate)
                  for view in (self.index_table, self.column_table, self.category_table):
                      if isinstance(model := view.model(), TranslateMixin):
                          model.set_translate(self._translate)
          
              @property
              def df(self) -> Any:
                  return self.holder.df
          
              def set_df(self, df: Any):
                  self.holder.df = df
          
              def _setup_models(self, is_pandas: bool):
                  """(Re)create the list models when the backend changes."""
                  self._is_pandas = is_pandas
                  for view in (self.index_table, self.column_table):
                      if (old := view.model()) is not None:
                          old.deleteLater()
                  if is_pandas:
                      index_model = pandasmodels.PandasIndexListModel(
                          self.holder, translate=self._translate
                      )
                      column_model = pandasmodels.PandasColumnListModel(
                          self.holder, translate=self._translate
                      )
                  else:
                      index_model = None
                      column_model = pandasmodels.SchemaModel(
                          self.holder, translate=self._translate
                      )
                  self.index_table.set_model(index_model)
                  self.column_table.set_model(column_model)
                  self.column_table.selectionModel().currentChanged.connect(self._on_current_change)
          
              def _on_df_changed(self, origin=None):
                  df = self.df
                  is_pandas = isinstance(df, pd.DataFrame)
                  if is_pandas != self._is_pandas:
                      self._setup_models(is_pandas)
                  attrs = df.attrs if is_pandas else {}
                  self.attrs_table.set_model(itemmodels.JsonModel(attrs, show_root=False))
          
              def _on_current_change(self, new: core.ModelIndex, old: core.ModelIndex):
                  source = self.holder.source
                  model = None
                  if new.isValid() and source is not None and new.row() < len(source.columns):
                      column_name = source.columns[new.row()].name
                      cls = (
                          pandasmodels.PandasCategoryListModel
                          if self._is_pandas
                          else pandasmodels.CategoryModel
                      )
                      model = cls(self.holder, column_name, translate=self._translate, parent=self)
                      try:
                          self.profile.set_column(self.holder, new.row())
                      except Exception:
                          logger.exception("Could not profile column %r", column_name)
                          self.profile.clear()
                  else:
                      self.profile.clear()
                  # Delete the previous model: it is connected to the holder and would
                  # otherwise stay alive (and keep resetting) for the widget's lifetime.
                  if (old_model := self.category_table.model()) is not None:
                      old_model.deleteLater()
                  self.category_table.set_model(model)
          

          retranslate

          retranslate()
          

          Re-show dock titles and panel labels with the current translate.

          Source code in src/cutepandas/pandaswidgets/dataframewidget.py
          def retranslate(self):
              """Re-show dock titles and panel labels with the current `translate`."""
              for dock, title in zip(self.docks, self.DOCK_TITLES):
                  dock.setWindowTitle(self._tr(title))
              self.profile.set_translate(self._translate)
              for view in (self.index_table, self.column_table, self.category_table):
                  if isinstance(model := view.model(), TranslateMixin):
                      model.set_translate(self._translate)
          

          GridDataFrameViewer

          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
          

          SimpleDataFrameViewer

          Bases: SortableViewerMixin, TableView

          Lightweight single-table viewer backed by DataFrameModel.

          Uses Qt's native horizontal and vertical QHeaderViews (joining MultiIndex levels with a separator) instead of separate header tables. Supports shared DataFrameHolders, dtype icons, clipboard copy/paste, and both "copy" and "permutation" sort modes with native sort indicators.

          Source code in src/cutepandas/pandaswidgets/simpledataframeviewer.py
          class SimpleDataFrameViewer(SortableViewerMixin, widgets.TableView):
              """Lightweight single-table viewer backed by `DataFrameModel`.
          
              Uses Qt's native horizontal and vertical `QHeaderView`s (joining MultiIndex
              levels with a separator) instead of separate header tables. Supports shared
              `DataFrameHolder`s, dtype icons, clipboard copy/paste, and both `"copy"` and
              `"permutation"` sort modes with native sort indicators.
              """
          
              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,
                  color_values: bool = False,
                  **kwargs,
              ) -> None:
                  super().__init__(**kwargs)
                  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)
          
                  self.setAlternatingRowColors(True)
                  self.set_scroll_mode("pixel")
                  self.setWordWrap(False)
                  self.set_size_policy("expanding", "expanding")
                  self.setItemDelegate(_viewer_style.DataCellDelegate(self))
          
                  self.h_header.setHighlightSections(True)
                  self.h_header.setSectionsClickable(True)
                  self.h_header.setSortIndicatorShown(False)
                  self.h_header.setStretchLastSection(False)
                  self.h_header.setDefaultAlignment(constants.ALIGN_CENTER)
                  self.h_header.sectionClicked.connect(self._on_header_clicked)
                  self.h_header.sectionHandleDoubleClicked.connect(self.auto_size_column)
          
                  self.v_header.setHighlightSections(True)
                  self.v_header.setDefaultAlignment(
                      constants.ALIGN_RIGHT | constants.ALIGN_V_CENTER
                  )
          
                  model = pandasmodels.DataFrameModel(
                      self.holder,
                      dtype_icons=dtype_icons,
                      color_values=color_values,
                      sort_mode=sort_mode,
                      parent=self,
                  )
                  self.set_model(model)
                  self.sorter = SortController(model, sortable=sortable, parent=self)
                  self._connect_sorter()
                  self.sorter.sort_state_changed.connect(self._on_sort_state_changed)
                  self.h_scrollbar.valueChanged.connect(self._autosize_visible_columns)
          
                  self._apply_style()
          
                  self.holder.changed.connect(self._on_df_changed)
                  self._on_df_changed()
          
              def _apply_style(self):
                  """Derive the colours from the palette (light or dark theme).
          
                  Only the viewport and the header widgets get palettes / style sheets, so the
                  view's own palette keeps following the application's.
                  """
                  colors = _viewer_style.ViewerColors.from_palette(self.palette())
                  self.setShowGrid(False)  # the delegate paints hairlines
                  viewport = self.viewport()
                  palette: Any = gui.QPalette(viewport.palette())
                  palette.setColor(gui.Palette.ColorRole.Base, colors.base)
                  palette.setColor(gui.Palette.ColorRole.AlternateBase, colors.alt_row)
                  viewport.setPalette(palette)
                  header_style = _viewer_style.native_header_style(colors)
                  self.h_header.setStyleSheet(header_style)
                  self.v_header.setStyleSheet(header_style)
                  _viewer_style.restyle_view(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()
          
              @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_df_changed(self, origin: Any = None):
                  self._autosized_cols.clear()
                  self._resize_columns_and_rows()
          
              def _resize_columns_and_rows(self):
                  model = self.model()
                  if model is None:
                      return
                  row_height = self.fontMetrics().height() + ROW_PADDING
                  self.v_header.setDefaultSectionSize(row_height)
                  for col in range(min(model.columnCount(), _viewer_style.AUTOSIZE_COLUMNS)):
                      self.auto_size_column(col)
          
              def _autosize_visible_columns(self, _value: int = 0):
                  """Lazily auto-size wide-frame columns as they scroll into view."""
                  model = self.model()
                  if model is None:
                      return
                  col_count = model.columnCount()
                  if len(self._autosized_cols) >= col_count:
                      return
                  vp_width = self.viewport().width()
                  first = self.columnAt(0)
                  if first < 0:
                      return
                  last = self.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` to its header (including icon/sort arrow) and first rows."""
                  self._autosized_cols.add(column_index)
                  model = self.model()
                  if model is None or not 0 <= column_index < model.columnCount():
                      return
                  header_text = model.headerData(
                      column_index, constants.HORIZONTAL, constants.DISPLAY_ROLE
                  )
                  rows = range(min(model.rowCount(), _viewer_style.SAMPLE_ROWS))
                  width = _viewer_style.fitted_column_width(
                      [str(header_text or "")],
                      self.h_header.font(),
                      (str(model.data(model.index(r, column_index)) or "") for r in rows),
                      self.fontMetrics(),
                      icon_space=_viewer_style.NATIVE_HEADER_ICON_SPACE if self._dtype_icons else 0,
                  )
                  self.setColumnWidth(column_index, width)
          
              # --- sorting ---
          
              def _on_header_clicked(self, column: int):
                  self.sorter.request_sort(column)
          
              def _on_sort_state_changed(self, state: tuple[int, constants.SortOrder] | None):
                  if state is None:
                      self.h_header.setSortIndicatorShown(False)
                  else:
                      self.h_header.setSortIndicator(*state)
                      self.h_header.setSortIndicatorShown(True)
          
              # --- clipboard ---
          
              def copy(self):
                  """Copy the bounding box of the selected cells as tab-separated text."""
                  indexes = self.selectionModel().selection().indexes()
                  model = self.get_model(skip_proxies=True)
                  if not indexes or model.source is None:
                      return
                  rows = [ix.row() for ix in indexes]
                  cols = range(
                      min(ix.column() for ix in indexes), max(ix.column() for ix in indexes) + 1
                  )
                  chunks = model.fetch_window(min(rows), max(rows) + 1, cols)
                  lines = [
                      "\t".join(
                          "" if chunk.values[i] is None else str(chunk.values[i])
                          for chunk in chunks
                      )
                      for i in range(max(rows) + 1 - min(rows))
                  ]
                  gui.GuiApplication.clipboard().setText("\n".join(lines))
          
              def paste(self):
                  """Paste tab-separated clipboard text, starting at the current cell."""
                  text = gui.GuiApplication.clipboard().text()
                  model = self.model()
                  if not text or model is None:
                      return
                  current = self.currentIndex()
                  top, left = (current.row(), current.column()) if current.isValid() else (0, 0)
                  for i, line in enumerate(text.splitlines()):
                      for j, cell in enumerate(line.split("\t")):
                          index = model.index(top + i, left + j)
                          if index.isValid():
                              model.setData(index, helpers.infer_type(cell), constants.EDIT_ROLE)
          
              def keyPressEvent(self, event: gui.QKeyEvent):
                  if event.matches(gui.KeySequence.StandardKey.Copy):
                      self.copy()
                  elif event.matches(gui.KeySequence.StandardKey.Paste):
                      self.paste()
                  else:
                      super().keyPressEvent(event)
          

          auto_size_column

          auto_size_column(column_index: int)
          

          Fit column_index to its header (including icon/sort arrow) and first rows.

          Source code in src/cutepandas/pandaswidgets/simpledataframeviewer.py
          def auto_size_column(self, column_index: int):
              """Fit `column_index` to its header (including icon/sort arrow) and first rows."""
              self._autosized_cols.add(column_index)
              model = self.model()
              if model is None or not 0 <= column_index < model.columnCount():
                  return
              header_text = model.headerData(
                  column_index, constants.HORIZONTAL, constants.DISPLAY_ROLE
              )
              rows = range(min(model.rowCount(), _viewer_style.SAMPLE_ROWS))
              width = _viewer_style.fitted_column_width(
                  [str(header_text or "")],
                  self.h_header.font(),
                  (str(model.data(model.index(r, column_index)) or "") for r in rows),
                  self.fontMetrics(),
                  icon_space=_viewer_style.NATIVE_HEADER_ICON_SPACE if self._dtype_icons else 0,
              )
              self.setColumnWidth(column_index, width)
          

          copy

          copy()
          

          Copy the bounding box of the selected cells as tab-separated text.

          Source code in src/cutepandas/pandaswidgets/simpledataframeviewer.py
          def copy(self):
              """Copy the bounding box of the selected cells as tab-separated text."""
              indexes = self.selectionModel().selection().indexes()
              model = self.get_model(skip_proxies=True)
              if not indexes or model.source is None:
                  return
              rows = [ix.row() for ix in indexes]
              cols = range(
                  min(ix.column() for ix in indexes), max(ix.column() for ix in indexes) + 1
              )
              chunks = model.fetch_window(min(rows), max(rows) + 1, cols)
              lines = [
                  "\t".join(
                      "" if chunk.values[i] is None else str(chunk.values[i])
                      for chunk in chunks
                  )
                  for i in range(max(rows) + 1 - min(rows))
              ]
              gui.GuiApplication.clipboard().setText("\n".join(lines))
          

          paste

          paste()
          

          Paste tab-separated clipboard text, starting at the current cell.

          Source code in src/cutepandas/pandaswidgets/simpledataframeviewer.py
          def paste(self):
              """Paste tab-separated clipboard text, starting at the current cell."""
              text = gui.GuiApplication.clipboard().text()
              model = self.model()
              if not text or model is None:
                  return
              current = self.currentIndex()
              top, left = (current.row(), current.column()) if current.isValid() else (0, 0)
              for i, line in enumerate(text.splitlines()):
                  for j, cell in enumerate(line.split("\t")):
                      index = model.index(top + i, left + j)
                      if index.isValid():
                          model.setData(index, helpers.infer_type(cell), constants.EDIT_ROLE)
          

          set_df

          set_df(df: Any)
          

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

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

          TopValuesModel

          Bases: TranslatableHeaderMixin, AbstractTableModel

          Most frequent values of a column: value, count and share of all rows.

          Source code in src/cutepandas/pandaswidgets/columnprofilewidget.py
          class TopValuesModel(TranslatableHeaderMixin, core.AbstractTableModel):
              """Most frequent values of a column: value, count and share of all rows."""
          
              HEADER: ClassVar[list[str]] = [N_("Value"), N_("Count"), N_("Share")]
          
              def __init__(
                  self,
                  top: Sequence[tuple[Any, int]] = (),
                  total: int = 0,
                  *,
                  translate: Translate | None = None,
                  **kwargs,
              ):
                  super().__init__(**kwargs)
                  self._translate = translate
                  self._top = list(top)
                  self._total = total
                  self._max = max((count for _, count in self._top), default=0)
          
              def rowCount(self, parent: core.ModelIndex | None = None) -> int:
                  return 0 if parent is not None and parent.isValid() else len(self._top)
          
              def columnCount(self, parent: core.ModelIndex | None = None) -> int:
                  return 0 if parent is not None and parent.isValid() else len(self.HEADER)
          
              def data(
                  self,
                  index: core.ModelIndex,
                  role: constants.ItemDataRole = constants.DISPLAY_ROLE,
              ):
                  if not index.isValid():
                      return None
                  value, count = self._top[index.row()]
                  match role, index.column():
                      case constants.DISPLAY_ROLE, 0:
                          return format_name(value)
                      case constants.DISPLAY_ROLE, 1:
                          return str(count)
                      case constants.DISPLAY_ROLE, 2:
                          return f"{count / self._total:.1%}" if self._total else ""
                      case constants.ALIGNMENT_ROLE, 1 | 2:
                          return constants.ALIGN_RIGHT | constants.ALIGN_V_CENTER
                      case DataFrameModel.Roles.NormalizedRole, 2:
                          return count / self._max if self._max else None
                      case constants.USER_ROLE, _:
                          return value
                  return None