46

I have QTableView and QAbstractTableModel. I require rows to have height equal to 24. I know the only way to do this is by calling QTableView::setRowHeight. Since the model is dynamic it may be added new rows, but I don't want to call setRowHeight each time new row is added.

How can I configure QTableView such that it uses the same height for new added rows or can a model be sent the height of rows?

Ed Holloway-George
  • 5,092
  • 2
  • 37
  • 66
Ashot
  • 10,807
  • 14
  • 66
  • 117

1 Answers1

95

For Qt versions < 5

QHeaderView *verticalHeader = myTableView->verticalHeader();
verticalHeader->setResizeMode(QHeaderView::Fixed);
verticalHeader->setDefaultSectionSize(24);

For Qt versions >= 5 use

QHeaderView *verticalHeader = myTableView->verticalHeader();
verticalHeader->setSectionResizeMode(QHeaderView::Fixed);
verticalHeader->setDefaultSectionSize(24);

If that function doesn't apply to vertical headers, you likely will have to call setRowHeight() every time you add a new row.

Cory Klein
  • 51,188
  • 43
  • 183
  • 243
  • 1
    I think it's better to give a name to the pointer different from the function name, otherwise you may have name conficts, e.g. if you do this from QTableView constructor QHeaderView *vh = myTableView->verticalHeader(); – Llopeth Jul 09 '19 at 12:32
  • If `verticalHeader` is already in scope, then just call `setResizeMode` and `setDefaultSectionSize` on it directly, no need to be worried about variable shadowing and no need to copy a local pointer. – Cory Klein Oct 25 '19 at 20:24
  • 4
    `QHeaderView` bounds the value passed to `setDefaultSectionSize` so you might need to call `setMinimumSectionSize` and `setMaximumSectionSize` before setting the default size. – MattBas Aug 29 '20 at 18:46