views:

39

answers:

1

Have written the following code:

m_selectCategoryTableWidget = new QTableWidget;
m_selectCategoryTableWidget->setRowCount(0);
m_selectCategoryTableWidget->setColumnCount(2);

m_selectCategoryTableWidget->setHorizontalHeaderLabels(QStringList()<<tr("Category")<<tr("Number of items"));
m_selectCategoryTableWidget->verticalHeader()->setVisible(false);
m_selectCategoryTableWidget->horizontalHeader()->setStretchLastSection(true);
//m_selectCategoryTableWidget->setColumnWidth(0,400);
m_selectCategoryTableWidget->resizeColumnsToContents();
m_selectCategoryTableWidget->setColumnWidth(1,100); //this does not take effect

Please help.

+1  A: 

Well, Qt's logic is so, that after column resize, scroll bar area checks how columns fit into it. And if the sum of all columns' widths is less than the widget's visible width, then the last column gets resized to fill up the space leading to no visible result of calling setColumnWidth(). Actually two resizes happen - to shrink and reverse to enlarge.

So, the lesson is - get control's visible width, recalculate sizes as you want, and resize all but the last column. For two column case it's really simple:

int secondColumnWidth = 100;
int firstColumnWidth = m_selectCategoryTableWidget->width() - secondColumnWidth;

if (firstColumnWidth > 0)
{
    m_selectCategoryTableWidget->setColumnWidth(0, firstColumnWidth);
}
else
{
    m_selectCategoryTableWidget->resizeColumnsToContents();
}

Good luck!

Sergei Eliseev
Hi, I've overlooked QHeaderView's property "stretchLastSection": http://doc.qt.nokia.com/4.6/qheaderview.html#stretchLastSection-propSetting this to 'false' will let you change last column's width freely, however to keep control looking nice you'd have to apply solution described above.
Sergei Eliseev