PDA

View Full Version : QTableView/QTableWidget and resizeRowsToContents resizes wrongly



alterro
28th August 2015, 09:55
I have a small issue. I'm trying to resize rows to its content. So in order to do that, I use resizeRowsToContents() method. But something funny is happening. I would like to call this function from a constructor because data won't change anymore so I want to resize them only once. But when I do that, rows are indeed resized but a bit larger than they suppose to be. And when I call this function once again (button click), rows will be resize properly.
So my question is why resizeRowsToContents doesn't work properly when it's called from a constructor?



MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
QTableWidgetItem *item;

ui->setupUi(this);
ui->tableWidget->verticalHeader()->hide();
ui->tableWidget->insertRow(0);
item = new QTableWidgetItem("aaa bbb ccc ddd eee fff ggg hhh iii jjj kkk lll mmm nnn ooo ppp");
ui->tableWidget->setItem(0, 0, item);
ui->tableWidget->resizeRowsToContents(); // resizes but the row is bigger than a content
}

void MainWindow::on_pushButton_clicked() {
ui->tableWidget->resizeRowsToContents(); // that will resize properly
}


Without resize
11342

Resize called from a constructor
11343

Resize called from clicked method
11344

alterro
31st August 2015, 12:11
I've found it. The code should look like this:



...
ui->tableWidget->setItem(0, 0, item);
show(); // show the widget so the last column can be resized and the next function will have a proper column size
ui->tableWidget->resizeRowsToContents();
...