QTableView subclass - Am I reinventing the wheel?
-
TL;DR: I'm a retired developer with about 20 years Java back-end experience, learning Qt for some volunteer non-profit development work. I wanted a QTableView with what I thought would be pretty standard resizing behaviors. I got it to work mostly, but was surprised that it took so much code. I guess I wasn't expecting to have to work down at the pixel level and thought a lot of this would be "standard".
So my questions is whether I'm reinventing something that already exists somewhere. I found some libraries but they seem to be more focused on filtering and Excel-like features.
Here's a summary of the requirements vis-a-vis resizing:
- Table's initial column widths are set so that no headers or data are truncated
- Column widths can be resized by the user (ResizeMode.Interactive)
- Each column has a minimum width below which it will not resize
- The entire table has a minimum width, based on the initial widths. It can be made wider but not narrower.
- As the containing window is resized horizontally, columns resize proportionally.
Below is what I ended up with. There are still a couple of minor glitches that mean I haven't quite understood some corner cases, but I can fix those.
Does this already exist somewhere?
Am I in the weeds, or is this just what it takes?BTW, I'm really impressed with Qt in general and plan to dig much deeper into it. I'm just a bit worried that I took a wrong turn somewhere :-)
import logging; log = logging.getLogger(__name__) from PySide6.QtWidgets import QTableView, QHeaderView from PySide6.QtCore import Qt, QSignalBlocker from PySide6.QtWidgets import QAbstractItemView as qv class SMTableView(QTableView): """ Subclass of QTableView with the following behaviors * Table's initial column widths are set so that all data is visible * Column widths can be resized by the user (ResizeMode.Interactive) * Each column has a minimum width below which it will not resize * The entire table has a minimum width, based on the initial widths * As the containing window is resized horizontally, columns resize proportionally. """ def __init__(self, parent=None): super().__init__(parent) # Number of columns in the model; -1 until we have a valid attached model self.nc = -1 # Current column widths self.columnWidths = None # Column widths relative to overall viewport width self.columnRatios = None hdr = self.horizontalHeader() # returned value is a wrapper to an ephemeral C++ object # Configure QTableView options hdr.setSectionResizeMode(QHeaderView.ResizeMode.Interactive) hdr.setHighlightSections(False) hdr.sectionResized.connect(self.onSectionResized) self.setFocusPolicy(Qt.FocusPolicy.NoFocus) self.setSelectionBehavior(qv.SelectionBehavior.SelectRows) self.setSelectionMode(qv.SelectionMode.SingleSelection) self.setAlternatingRowColors(True) self.setSizeAdjustPolicy(QTableView.SizeAdjustPolicy.AdjustToContents) def isValid(self) -> bool: return self.nc > 0 def applyRatios(self): ''' Distribute the current relative column width ratios across all columns after a resize event ''' if not self.isValid(): return hdr = self.horizontalHeader() # returned value is a wrapper to an ephemeral C++ object available_width = self.viewport().width() if available_width <= 0: return used_width = 0 # Update all but the last column based on the new viewport width # and the current relative ratios for i in range(self.nc-1): curWidth = self.columnWidths[i] newWidth = int(round(available_width * self.columnRatios[i])) if newWidth != curWidth: hdr.resizeSection(i, newWidth) self.columnWidths[i] = newWidth used_width += newWidth # For the last column, to avoid roundoff problems, # resize to the remaining width in the viewport hdr.resizeSection(self.nc-1, max(0, available_width-used_width)) # Note: We DO NOT update the ratios here (as was suggested in several forums) def captureCurrentRatios(self): ''' Calculate the current column width ratios ''' if not self.isValid(): return widths = [self.columnWidth(i) for i in range(self.nc)] total = sum(widths) self.columnRatios = [w / total for w in widths] def onSectionResized(self, col:int, oldSize:int, newSize:int): if not self.isValid(): return hdr = self.horizontalHeader() # returned value is a wrapper to an ephemeral C++ object minWidth = self.minWidths[col] newWidth = newSize # If we attempt to resize below the minimum width force the width # back to the minimum while blocking resize event signals if newWidth < minWidth: newWidth = minWidth with QSignalBlocker(hdr): hdr.resizeSection(col, newWidth) log.debug(f"Section: col {col} {oldSize} -> {newWidth}") def setModel(self, model): ''' Attach the model ''' super().setModel(model) self.nc = model.columnCount() hdr = self.horizontalHeader() # returned value is a wrapper to an ephemeral C++ object # Get initial column widths as max(headerWidth,columnWidth) # This will be updated as column widths change self.columnWidths = [max(self.sizeHintForColumn(i), hdr.sectionSizeHint(i)) for i in range(self.nc)] # Save these as the minimum allowable column widths # Probably need some logic to gracefully handle excessive minimum widths; TBD self.minWidths = self.columnWidths.copy() # Set the minimum width for the entire QTableView self.setMinimumWidth(sum(self.minWidths)) # Establish the current column width ratios self.captureCurrentRatios() def resizeEvent(self, event): ''' Handle an event indicating the QTableView is being resized, probably as a result of the window being resized ''' super().resizeEvent(event) newWidth = event.size().width() oldWidth = event.oldSize().width() if oldWidth < 0 or newWidth == oldWidth: return self.applyRatios() def resizeColumnsToContents(self): ''' Override to capture column width ratios ''' super().resizeColumnsToContents() self.captureCurrentRatios()