Skip to content

DataFrameViewer

Base classes

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

â‹” Inheritance diagram

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

🛈 DocStrings

Bases: SortableViewerMixin, Widget

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

:fa-brands-github: Show source on GitHub