我正在开发一个使用QTableWidget
来显示数据的C ++ Qt应用程序。
据我所知,QTableWidget
为列提供自动调整大小模式:调整最后一个。
这种方法不适合我的任务,所以我用QTableWidget
函数编写了继承自resizeEvent
的新类:
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 ) );
}
}
我添加了4列并设置了以下相对宽度值(它们的总和 1000 ):
| First column | Second column | Third column | Fourth column |
| 100 | 140 | 380 | 380 |
然而,在表的宽度小于 1000 之前,我看不到表格中的任何列。
使用调试模式,如果point
为真,我看到变量width < totalPoints
等于 0 。例如,如果width
等于 762 ,则point
应 0.762 ,但 0 。
看起来程序会自动舍入double
值。为什么?我做错了什么?
也许有更好的方法来完成我的任务(使用QTableWidget
中的百分比列宽度?)
答案 0 :(得分:1)
width
和totalPoints
都是整数。所以你得到一个整数除法,每当width < totalPoints
时都会得到零。
将其中一个投放到double
:
double point = width / (double) totalPoints;