<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[QTableView subclass - Am I reinventing the wheel?]]></title><description><![CDATA[<p dir="auto">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".</p>
<p dir="auto">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.</p>
<p dir="auto">Here's a summary of the requirements vis-a-vis resizing:</p>
<ul>
<li>Table's initial column widths are set so that no headers or data are truncated</li>
<li>Column widths can be resized by the user (ResizeMode.Interactive)</li>
<li>Each column has a minimum width below which it will not resize</li>
<li>The entire table has a minimum width, based on the initial widths.  It can be made wider but not narrower.</li>
<li>As the containing window is resized horizontally, columns resize proportionally.</li>
</ul>
<p dir="auto">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.</p>
<p dir="auto">Does this already exist somewhere?<br />
Am I in the weeds, or is this just what it takes?</p>
<p dir="auto">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 :-)</p>
<pre><code>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) -&gt; bool:
        return self.nc &gt; 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 &lt;= 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 &lt; minWidth:
            newWidth = minWidth
            with QSignalBlocker(hdr):
                hdr.resizeSection(col, newWidth)
        log.debug(f"Section: col {col}   {oldSize} -&gt; {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 &lt; 0 or newWidth == oldWidth: return
        self.applyRatios()
        
    def resizeColumnsToContents(self):
        ''' Override to capture column width ratios
        '''
        super().resizeColumnsToContents()
        self.captureCurrentRatios()
</code></pre>
]]></description><link>https://forum.qt.io/topic/165310/qtableview-subclass-am-i-reinventing-the-wheel</link><generator>RSS for Node</generator><lastBuildDate>Mon, 30 Nov 2026 02:50:33 GMT</lastBuildDate><atom:link href="https://forum.qt.io/topic/165310.rss" rel="self" type="application/rss+xml"/><pubDate>Mon, 30 Nov 2026 01:28:34 GMT</pubDate><ttl>60</ttl></channel></rss>