Resize Column Width QTableWidget

18,872

Considering that you are using Qt5, give a try to

QTableWidget* mainList = new QTableWidget;
QHeaderView* header = mainList ->horizontalHeader();
header->setSectionResizeMode(QHeaderView::Stretch);

OR

There is a header flag to ensure that the QTableView's last column fills up its parent if resized.

header->setStretchLastSection(true);
Share:
18,872
ayasha
Author by

ayasha

Updated on July 10, 2022

Comments

  • ayasha
    ayasha almost 2 years

    I have this widget created with QTableWidget: enter image description here

    and I would like that the column of my table resize in order to occupy the entire width of the widget, while for the rows is ok as it is. I know there is a similar question like mine but I was not able to solve it in that way.. This is my code

    void MainWindow::createTable(int rows, int columns) {
        mainList = new QTableWidget;
        QStringList headerLabels;
        headerLabels << "Title" << "Director" << "Year" << "Counter" << "Rating";
        mainList->setRowCount(rows);
        mainList->setColumnCount(columns);
        mainList->setHorizontalHeaderLabels(headerLabels);
        mainList->setEditTriggers(QAbstractItemView::DoubleClicked | QAbstractItemView::SelectedClicked);
        mainList->setSelectionBehavior(QAbstractItemView::SelectRows);
        mainList->resizeColumnsToContents();
        mainList->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    
        setCentralWidget(mainList);
    }
    
  • Davor
    Davor over 9 years
    I'd just add that if you want to have non-last column take all remaining space you should write: "ui->table->horizontalHeader()->setSectionResizeMode(columnI‌​ndex, QHeaderView::Stretch);"