Skip to content
Qt 6.12 LTS is out! See what's new in the release blog
  • 145k Topics
    725k Posts
    J
    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()
  • Jobs, project showcases, announcements - anything that isn't directly development
    4k 23k
    4k Topics
    23k Posts
    SGaistS
    Hi and welcome to devnet, Moved it to showcase as I think it's more fitting to demonstrate your project :-)
  • Everything related to designing and design tools

    135 411
    135 Topics
    411 Posts
    A
    Subject: Qt Design Studio 4.8: custom QML module is recognised and runs, but its section in the Components panel lists no items (designer/*.metainfo) Hi all, I have a small custom QML module that I want to appear as drag-and-drop items in the Components panel. The module resolves and runs, but its section in the Components panel has no arrow and no items. I have followed the documented steps and compared my files against Qt's own, and I am out of ideas. Any pointers would be appreciated. Environment Qt Design Studio 4.8 (qmlpuppet 4.8.3); kit in the status bar shows "Designer Qt 6.8.7" Windows, MSVC 2022 (x64), CMake with Ninja Module built with Qt 6.8.3 for MSVC 2022 64-bit (the only 6.8 kit the maintenance tool offered) Project file has enableCMakeGeneration: true The module (dummy names) A module "MyModule" with three plain QML types: ItemA, ItemB and ItemC (QtQuick only, no C++ code of my own). Folder form: MyModule/ qmldir ItemA.qml, ItemB.qml, ItemC.qml designer/ plugin.metainfo images/*.png (16px and 24px icons) qmldir: module MyModule typeinfo plugins.qmltypes ItemA 1.0 ItemA.qml ItemB 1.0 ItemB.qml ItemC 1.0 ItemC.qml designersupported plugin.metainfo (one Type shown, the others are the same shape): MetaInfo { Type { name: "MyModule.ItemA" icon: "images/itema-16px.png" Hints { visibleInNavigator: true; canBeDroppedInNavigator: true; canBeDroppedInFormEditor: true; canBeContainer: false; visibleInLibrary: true } ItemLibraryEntry { name: "ItemA" category: "My Category" libraryIcon: "images/itema-24px.png" version: "1.0" requiredImport: "MyModule" toolTip: qsTr("A sample item.") } } } I also built it as a module with qt_add_qml_module (URI MyModule, version 1.0, SHARED, DESIGNER_SUPPORTED, PLUGIN_TARGET set to the module's own target so that it is a single DLL) and copied the designer folder next to the generated qmldir. What happens "Add a Module" in the Components panel does not list MyModule. If I type "import MyModule" in the .ui.qml file, a "MyModule" section appears in the panel, but it cannot be expanded and has no items. importPaths in the .qmlproject: if the module sits outside the project folder (absolute path), the canvas and Navigator cannot resolve its types (no warning), although the app runs. If the module is inside the project ("imports" and "." in importPaths), the types resolve, appear in the Navigator and canvas, and their properties are editable. The Components panel stays empty in both cases. Built module with the .qml files present: same as 2 (types resolve, panel empty). Built module with the .qml files removed and a single DLL: the Run button works, but the types disappear from the canvas and Navigator. So the editor seems to need the .qml source, while the runtime can use the compiled module. The Issues and Output panels show no errors after I declared the module's folder in the project file (QmlFiles, ImageFiles, and Files for qmldir and *.metainfo). Design Studio's own qml.exe and Qt 6.8.3's qml.exe both load the built module and show the types, so the module itself is valid. What I have tried (no change in the Components panel) Icon references as :/qtquickplugin/..., :/ItemLibrary/..., and relative paths to PNGs next to the metainfo file; with and without libraryIcon, Hints and toolTip One metainfo file per type, then a single plugin.metainfo A stub plugins.qmltypes with a typeinfo line Keeping two copies of the module identical, in case a stale one was being read Closing and reopening the project after every change Comparing against Design Studio's built-in itemLibrary/*.metainfo files and Qt's QtQuick/Controls/designer/qtquickcontrols2.metainfo: the structure of mine is the same Following the six documented steps, including building the module with a Qt of the same minor version as Design Studio (6.8.3 against 6.8.7) [image: 6502e6a2-170b-491a-b49f-60c4f885ea37.png] Questions Is a QML-only module with designer/*.metainfo supposed to populate the Components panel in 4.8, or does it need a C++ plugin type or some other structure? Is there a log or environment variable that shows whether and why a metainfo file is rejected? I see nothing in Output or Issues. Is there a cache for item-library entries that needs clearing, and where is it stored? Does the editor really need the .qml source of a custom module to show its types, or is there a way to give it a compiled-only module? I can attach the module folder and the .qmlproject if that helps. Thanks in advance.
  • Everything related to the Software Quality Tools

    97 272
    97 Topics
    272 Posts
    C
    This had been reported to Squish technical support team, and closed on behalf of the reporter. Unfortunately it was not possible to identify a clear cause so far.
  • Everything related to learning Qt.

    406 2k
    406 Topics
    2k Posts
    A
    [image: 8eb48c3b-acfe-413e-a66c-abdccae786dc.png]
  • 2k Topics
    13k Posts
    jsulmJ
    @VikMorroHun said in blocked: cmake: command not found: In Linux I got more than 6000 hits How did you search to get 6000 hits?
  • 4k Topics
    18k Posts
    C
    找到原因了,账号密码错误导致的
  • This is where all the posts related to the Qt web services go. Including severe sillyness.
    1k 10k
    1k Topics
    10k Posts
    P
    Unless I misunderstand, this topic was written when this forum used Textile, which explains why some of the above have broken formatting. This question is therefore no longer relevant for this forum. That being said, to anwer this question should anyone else land on this topic from a search engine, this should (now?) be possible. 🅭🄍