adjusting window size to table contents



  • I'm trying to display a table, with the size of the window automatically adjusted to the contents of the table, at least horizontally. I can't get it to work: the "standard" window width always remains smaller than needed to fully display the content.

    I have a minimal example based on a new Widget project created by QtCreator. In QtDesigner I place a QTableWidget inside the QMainWindow. For the purpose of the example I configure it to 1 row, 2 columns, with the text in the second column made longer than a "standard" width.

    To get the QTableWidget itself to adjust to the content, I add

    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
    

    to the constructor for the main window (I couldn't find a QtDesigner setting for this use of ResizeToContents).

    I set the mainwindow layout to vertical (assigned to centralWidget). If I understood correctly, this is supposed to automatically adjust the window width to the width of the contents.

    But instead, the window is created to a size smaller than the width of the table. I can change the size manually (with the mouse). But I can't see how to adjust it automatically. mainWindow->adjustSize() sets it back to the original state, with the window width smaller than the table width.

    Is there something else I need to be doing?



  • Here is the minimal test case:

    mainwindow.cpp

    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    
    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
    
        ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
    
    }
    
    MainWindow::~MainWindow()
    {
        delete ui;
    }
    

    mainwindow.ui

    <?xml version="1.0" encoding="UTF-8"?>
    <ui version="4.0">
     <class>MainWindow</class>
     <widget class="QMainWindow" name="MainWindow">
      <property name="geometry">
       <rect>
        <x>0</x>
        <y>0</y>
        <width>400</width>
        <height>300</height>
       </rect>
      </property>
      <property name="windowTitle">
       <string>MainWindow</string>
      </property>
      <widget class="QWidget" name="centralWidget">
       <layout class="QVBoxLayout" name="verticalLayout">
        <item>
         <widget class="QTableWidget" name="tableWidget">
          <property name="sizePolicy">
           <sizepolicy hsizetype="Preferred" vsizetype="Expanding">
            <horstretch>0</horstretch>
            <verstretch>0</verstretch>
           </sizepolicy>
          </property>
          <property name="sizeAdjustPolicy">
           <enum>QAbstractScrollArea::AdjustToContents</enum>
          </property>
          <property name="wordWrap">
           <bool>false</bool>
          </property>
          <property name="rowCount">
           <number>1</number>
          </property>
          <property name="columnCount">
           <number>2</number>
          </property>
          <attribute name="horizontalHeaderVisible">
           <bool>false</bool>
          </attribute>
          <attribute name="horizontalHeaderCascadingSectionResizes">
           <bool>false</bool>
          </attribute>
          <attribute name="horizontalHeaderStretchLastSection">
           <bool>false</bool>
          </attribute>
          <attribute name="verticalHeaderVisible">
           <bool>false</bool>
          </attribute>
          <row/>
          <column/>
          <column/>
          <item row="0" column="0">
           <property name="text">
            <string>col 1</string>
           </property>
          </item>
          <item row="0" column="1">
           <property name="text">
            <string>This is an entry which is longer than the &quot;standard&quot; width.</string>
           </property>
          </item>
         </widget>
        </item>
       </layout>
      </widget>
      <widget class="QMenuBar" name="menuBar">
       <property name="geometry">
        <rect>
         <x>0</x>
         <y>0</y>
         <width>400</width>
         <height>19</height>
        </rect>
       </property>
      </widget>
      <widget class="QToolBar" name="mainToolBar">
       <attribute name="toolBarArea">
        <enum>TopToolBarArea</enum>
       </attribute>
       <attribute name="toolBarBreak">
        <bool>false</bool>
       </attribute>
      </widget>
      <widget class="QStatusBar" name="statusBar"/>
     </widget>
     <layoutdefault spacing="6" margin="11"/>
     <resources/>
     <connections/>
    </ui>
    

    Other files are unchanged from the QtCreator widget project:

    mainwindow.h

    #ifndef MAINWINDOW_H
    #define MAINWINDOW_H
    
    #include <QMainWindow>
    
    namespace Ui {
    class MainWindow;
    }
    
    class MainWindow : public QMainWindow
    {
        Q_OBJECT
    
    public:
        explicit MainWindow(QWidget *parent = 0);
        ~MainWindow();
    
    private:
        Ui::MainWindow *ui;
    };
    
    #endif // MAINWINDOW_H
    
    

    main.cpp

    #include "mainwindow.h"
    #include <QApplication>
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        MainWindow w;
        w.show();
    
        return a.exec();
    }
    
    


  • Project file is also unchanged from the one generated by QtCreator:

    TestTable.pro

    #-------------------------------------------------
    #
    # Project created by QtCreator 2017-01-04T17:28:55
    #
    #-------------------------------------------------
    
    QT       += core gui
    
    greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
    
    TARGET = TestTable
    TEMPLATE = app
    
    # The following define makes your compiler emit warnings if you use
    # any feature of Qt which as been marked as deprecated (the exact warnings
    # depend on your compiler). Please consult the documentation of the
    # deprecated API in order to know how to port your code away from it.
    DEFINES += QT_DEPRECATED_WARNINGS
    
    # You can also make your code fail to compile if you use deprecated APIs.
    # In order to do so, uncomment the following line.
    # You can also select to disable deprecated APIs only up to a certain version of Qt.
    #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0
    
    
    SOURCES += main.cpp\
            mainwindow.cpp
    
    HEADERS  += mainwindow.h
    
    FORMS    += mainwindow.ui
    

  • Lifetime Qt Champion

    Hi,

    A layout doesn't necessarily make the container window bigger to accommodate the contained widget. By default it tries to fit everything in the hinted sizes (hints coming from the widgets in the layout).

    So if you have a QTableView which size should vary depending on its content, you have to add some logic to trigger the resize of the container widget.



  • Thanks @SGaist. The size of the QTableView itself is already being updated (setSectionResizeMode(QHeaderView::ResizeToContents) makes that happen). Do you mean I need to resize centralWidget, the component of the MainWindow in which the Table is placed? That doesn't seem to work though.

    If I manually trigger window->centralWidget()->adjustSize(); (window is the QMainWindow) then the frame around the table adjusts (to the default window size, not to the table size) and does not adjust the window size with it. If I trigger window->adjustSize(); then the window size does adjust, but again, not to the table size.



  • Hmm. My tests with adjustSize() were on my actual code, where triggering window->adjustSize() does not adjust to the table size.

    But when I add an Adjust Size trigger to my minimal test code, it does adjust to the table size. I'll have to work out what's different in the two cases.



  • Found it. The Qt Designer configuration block for the QTableWidget includes QAbstractScrollArea with property sizeAdjustPolicy. I need to set it to AdjustToContents to get the behaviour I want.

    I still need to trigger window->adjustSize() to make the window catch up with the table size (or more precisely, with the size of its ScrollArea).

    Thanks for your help.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.