QTableView give columnwidth a percentage and keep percentage when table gets wider



  • I have looked at various posts on this, but not found a solution.
    I am using a model in a QTableView.

    At the moment I am not setting column widths, but just stretching the righthand column.

    ui->contentTable->horizontalHeader()->stretchLastSection();
    

    What I really want to do is this. I have a two column table.
    I want to give the first column 20% width and the second column 80% width.

    When the table expands I want them to keep these width percentages, but expand.

    I have tried

     ui->contentTable->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch);
      ui->contentTable->horizontalHeader()->setSectionResizeMode(3, QHeaderView::Stretch);
    

    But this just make equal size columns.
    By the way 2 and 3 is not an error, as the first column is hidden because that is where I store the id for sqlite.

    I have tried setting the second column width like this

    ui->contentTable->setColumnWidth(2,100);
    

    but this isn't a percentage and stays fixed at this width.

    So is there a way of using percentages for table column widths?


  • Lifetime Qt Champion

    Hi,

    The solution described here might be of interest.



  • @SGaist
    Strangely enough I found this page while searching, but none of the solutions on the page seemed to work.

    However I have re-looked at the page and this is my solution to my problem.

    I set the last column to stretch like before

    ui->contentTable->horizontalHeader()->setSectionResizeMode(3, QHeaderView::Stretch);
    

    and then I use a bit of code off the other page you gave me.

    void MainWindow::resizeEvent(QResizeEvent *event) {
        ui->contentTable->setColumnWidth(2, this->width()/5);
        QMainWindow::resizeEvent(event);
    }
    

    This gives me a wider first column which is column 2 and it stretches in proportion to the full screen.

    Thanks, this is solved.
    My new app is nearly finished.


Log in to reply