Qt setColumnWidth does not work

Have written the following code:

m_selectCategoryTableWidget = new QTableWidget;

m_selectCategoryTableWidget->setHorizontalHeaderLabels(QStringList()<<tr("Category")<<tr("Number of items"));
m_selectCategoryTableWidget->setColumnWidth(1,100); //this does not take effect

Please help.


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);

Good luck!

It is also possible to specify that you want the first column to fill the remaining space instead of the last column. Unfortunately this does seem to prevent the user from being able to manually resize the columns.

int secondColumnWidth = 100;
m_selectCategoryTableWidget->header()->setResizeMode(0, QHeaderView::Stretch);
m_selectCategoryTableWidget->setColumnWidth(1, secondColumnWidth);

This will automatically resize the columns to fit ("view" is an QTableView* and model is a QSqlQueryModel*).


QFontMetrics fm(view->font());

for (int i = 0 ; i < model->record().count(); ++i)
    int maxLength = 0;

    for (int j = 0; j < model->rowCount(); ++j)
        QString cell = model->record(j).value(i).toString();

        if (fm.width(cell) > maxLength)
            maxLength = fm.width(cell);
    QHeaderView& hv = *static_cast<QTableView*>(view)->horizontalHeader();

    if (maxLength > hv.sectionSize(i))
        hv.resizeSection(i, maxLength * 1.5);

Need Your Help

Reusable android styles?

android themes android-styles

I can't seem to be able to find any existing android styles.