【发布时间】:2013-05-05 09:40:25
【问题描述】:
我正在开发一个 C++ Qt 应用程序,它使用 QTableWidget 来显示数据。
据我所知,QTableWidget 为列提供了自动调整大小的模式:调整最后一个的大小。
这种方法不适合我的任务,所以我用resizeEvent函数编写了继承自QTableWidget的新类:
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 之前,我看不到表格中的任何列。
使用调试模式,如果width < totalPoints 为真,我看到变量point 等于0。例如,如果width 等于 762,point 应该是 0.762,但它是 0。
看起来程序会自动舍入double 值。为什么?我做错了什么?
也许有更好的方法来完成我的任务(在QTableWidget 中使用百分比列宽)?
【问题讨论】:
标签: c++ qt width qtablewidget