How to get a QTableView to fill 100% of the width?

Here's a print screen of my software:

As you can see, the first QTableVIew headers do not take 100% of the width. In fact, there is a small vertical white space on the right of the field size.

How can I get the headers to take 100% of the width of the QTableView?

Answers


If you are using Qt 5, QHeaderView::setResizeMode() is no longer available. Instead, you can use QHeaderView::setSectionResizeMode(). Just call it for every column:

for (int c = 0; c < ui->tableView->horizontalHeader()->count(); ++c)
{
    ui->tableView->horizontalHeader()->setSectionResizeMode(
        c, QHeaderView::Stretch);
}

Use view->horizontalHeader()->setStretchLastSection(true) to make the last column expand to free space.

Additionally, use view->horizontalHeader()->setResizeMode(QHeaderView::Stretch) to give columns the same width.


Here works using only with:

ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

I'm using Qt 5.2!


I had a hard time distributing column widths among all cells of a table. In my case, in headerData function of the model, I did the following (requires calling resizeColumnsToContents() somewhere):

QVariant headerData(int section, Qt::Orientation orientation, int role) const override {
  if (orientation == Qt::Vertical) {
    return QVariant();
  }
  if (role == Qt::SizeHintRole) {
    auto* p = qobject_cast<QTableView*>(QObject::parent());
    if (p == nullptr) return QVariant();
    // Parent total width.
    const int w = p->viewport()->size().width() -
        p->verticalScrollBar()->sizeHint().width();
    QSize qs;
    // Default height.
    qs.setHeight(p->verticalHeader()->defaultSectionSize());
    // Width per column.
    switch (section) {
      case 0:
        qs.setWidth(w * 0.45);
        return QVariant(qs);
      case 1:
        qs.setWidth(w * 0.45);
        return QVariant(qs);
      // ... others
      default: ;
    }
    return QVariant();
  }
  if (role == Qt::DisplayRole) {
    // header titles.
  }
}

Need Your Help

What is the difference between proofs and programs (or between propositions and types)?

lo.logic pl.programming-languages

Given that the Curry-Howard Correspondence is so widely spread/extended, is there any difference between proofs and programs (or between propositions and types)? Can we really identify them?

Running multiple instances of Rails Server

ruby-on-rails

I am new to Rails, so please forgive me if this is obvious.