Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Table header ResizeToContents and Stretch ?



  • Hi, is it possible to achieve something like a mix of the two ResizeModes of QHeaderView ? Firstly, I want the columns to be resized in such manner, that all content is visible. This is achieved using the ResizeToContents flag. Secondly, I want to stretch all columns(by the same factor) until the table fits the entire width of the widget.
    Is this doable ?



  • I dont't think there is a build in function for that, but you can do the following:

    • get total view width
    • calculate the size of each table entry (using QFontMetrics for text and size() for icons and so on
    • calculate the remaining width after each column has the width it needs for the content and distribute it equally to all the widths
    • setting the size by calling setColumnWidth() for each column


  • Thanks @gde23. Using your ideas, I think I found a better(easier) solution:

    1. Don't set the section resize mode to QHeaderView::ResizeToContents
    2. After modifying data in the table do:
    beerTable.resizeColumnsToContents();
    
    //followed by
    
    int widgetWidth = beerTable.viewport()->size().width();
    int tableWidth = 0;
    
    for(int i = 0; i<beerTable.columnCount(); ++i)
        tableWidth += beerTable.horizontalHeader()->sectionSize(i); //sections already resized to fit all data
    
    double scale = (double)widgetWidth/tableWidth;
    for(int i = 0; i<beerTable.columnCount(); ++i)
        beerTable.setColumnWidth(i, beerTable.horizontalHeader()->sectionSize(i) * scale);
    

Log in to reply