2

编写了以下代码:

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

请帮忙。

4

3 回答 3

3

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!

于 2010-07-07T14:20:42.870 回答
3

也可以指定您希望第一列填充剩余空间而不是最后一列。不幸的是,这似乎阻止了用户手动调整列的大小。

int secondColumnWidth = 100;
m_selectCategoryTableWidget->header()->setStretchLastSection(false);
m_selectCategoryTableWidget->header()->setResizeMode(0, QHeaderView::Stretch);
m_selectCategoryTableWidget->setColumnWidth(1, secondColumnWidth);
于 2011-06-15T13:36:19.650 回答
0

这将自动调整列的大小以适应(“view”是一个 QTableView*,model 是一个 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);
    }
}
于 2011-06-16T03:27:31.760 回答