开发者

Qt setColumnWidth does not work

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

Plea开发者_如何学Cse 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);
}
else
{
    m_selectCategoryTableWidget->resizeColumnsToContents();
}

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()->setStretchLastSection(false);
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*).

static_cast<QTableView*>(view)->horizontalHeader()
        ->resizeSections(QHeaderView::ResizeToContents);

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜