Resize QTableView / QSqlQueryModel

  • Hi, i have 2 problems (sorry my english is bad, let me know if you don't understand).

    1. Is their a way to use resizeColumnsToContents() and resizeSections(QHeaderView::ResizeMode::Stretch) at the same time ? Because if i used only resizeColumnsToContents it's like this (didn't feet the white space) : example
      And if i used resizeSections(QHeaderView::ResizeMode::Stretch) it's like this (some columns are unnecessarily large and some need to be large to display their content) : example

    2. At initialization the table is not affected by the resize methodes, i tried to setVisible(0 and 1) between resize but it doesn't work. Did you have an idea ?

    Thanks for helping me.

    2. could you try forcing a call to update() on the QTableView?

    1. Result :
      It's still looking bad. Is their a way to set an equal stretch between each columns ? Like that : example

    2. Apparantly not.

  • @Gaalee said in Resize QTableView / QSqlQueryModel:

    It's still looking bad. Is their a way to set an equal stretch between each columns ? Like that :


  • Doesn't work with resizeColumnsToContents().

  • Ok, now I understood, you want to equally distribute the extra space among the remaining columns.

    void resizeEvent(QResizeEvent *ev)
    Q_SLOT void resizeHeaders()
        QHeaderView* const tableHead = view->horizontalHeader();
        const int secCount = tableHead->count();
        if (view->model()->rowCount() == 0 || secCount<=1) {
        QVector<int> allHints(secCount);
        for (int i = 0; i < secCount; ++i)
            allHints[i]= tableHead->sectionSize(i);
        const int extraSpace = tableHead->width() - std::accumulate(allHints.constBegin(), allHints.constEnd(), 0);
        for (int i = 0; i < secCount; ++i)
            tableHead->resizeSection(i, + static_cast<int>(static_cast<double>(extraSpace) / static_cast<double>(secCount)));

    then in the constructor add

    connect(model, &QAbstractItemModel::rowsRemoved, this, &QuoteViewer::resizeHeaders);
        connect(model, &QAbstractItemModel::dataChanged, this, &QuoteViewer::resizeHeaders);

    This will distribute the extra space evenly, not based on the original size, it's trivial to modify the math to achieve this other result btw

Log in to reply

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