Important: Please read the Qt Code of Conduct -

QTableView auto column resize when new data is added

  • The documentation for QHeaderView::ResizeToContents states:

    bq. QHeaderView will automatically resize the section to its optimal size based on the contents of the entire column or row. The size cannot be changed by the user or programmatically. (This value was introduced in 4.2)

    It doesn't specify when this is actually done, and apparently it only happens at the moment the resize mode is set (e.g. via view->horizontalHeader()->setResizeMode()). The columns are resized when the mode is changed but are not resized as new data is added or existing data changes. This seems only marginally useful.

    When I search the internet for answers to this question, all answers suggest using ResizeToContents. I'm not sure why this is a popular answer -- as described above, this only resizes the columns once when it is set, and not in response to changing data.

    How do I have a QTableView that automatically resizes its columns to the content sizes when data in the table is modified?

    Right now I just have a timer on the main window that periodically sets the resize mode. It's very ugly to look at and seems like a silly solution.


  • @JCipriani
    I have faced the similar issue while implementing auto refresh table using QTableView. I am using Qt-4.8.5 and it seems like there is a bug about this behavior

    As a workaround I used the sectionHandleDoubleClicked() signal from the header view class and I emit that signal after creation of the Sub-classed table view

    For data change notification, with the help of QFileSystemWatcher, I monitor the file and when there is a modification, I reset the model and emit the same signal for column resize

Log in to reply