1
votes

I'm developing a C++ Qt application that uses QTableWidget to show data.

As far as I know, QTableWidget provides automatic resizing mode for columns: resize the last one.

This approach didn't fit for my task, so I wrote the new class inherited from QTableWidget with resizeEvent function:

MyTableWidget::MyTableWidget ( std::vector<int> columnsRelWidth )
{
    //columnsRelWidth contains relative width of each column in the table

    this->columnWidth = columnsRelWidth;
}

void MyTableWidget::resizeEvent ( QResizeEvent *event )
{
    QSize newSize = event->size();
    int totalPoints = 0; //total points of relative width
    for ( int x = 0; x < this->columnWidth.size(); ++x )
    {
        totalPoints += this->columnWidth[x];
    }
    int width = newSize.width();
    double point = width / totalPoints; //one point of relative width in px
    for ( int x = 0; x < this->columnCount(); ++x )
    {
        this->setColumnWidth ( x, ( this->columnWidth[x] * point ) );
    }
}

I added 4 columns and set the following relative width values (their sum is 1000):

| First column | Second column | Third column | Fourth column |
|     100      |      140      |     380      |      380      |

Nevertheless, I can't see any columns in the table until table's width is less that 1000. Using debug mode, I saw that variable point equals to 0 if width < totalPoints is true. For example, if width equals to 762, point should be 0.762, but it is 0.

It looks like program automatically rounds double value. Why? What am I doing wrong?

Maybe there are better ways to accomplish my task (use percent columns width in QTableWidget)?

1

1 Answers

1
votes

Both width and totalPoints are integers. So you get an integer division there, and that will result in zero whenever width < totalPoints.

Cast one of them to double:

double point = width / (double) totalPoints;