Columns auto-resize to size of QTableView

This code equally stretchs each columns so that they fit the table's width.

table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

Docs:

  • QHeaderView::setSectionResizeMode
  • See resize modes here.

There is a header flag to ensure that the QTableView's last column fills up its parent if resized. You can set it like so:

table_view->horizontalHeader()->setStretchLastSection(true);

However, that does not resize the other columns proportionately. If you want to do that as well, you could handle it inside the resizeEvent of your parent thusly:

void QParent::resizeEvent(QResizeEvent *event) {
    table_view->setColumnWidth(0, this->width()/3);
    table_view->setColumnWidth(1, this->width()/3);
    table_view->setColumnWidth(2, this->width()/3);

    QMainWindow::resizeEvent(event);
}

QParent class is subclass of QMainWindow.

Tags:

C++

Qt

Qtableview