3
votes

After filling a QTableWidget table I call:

table->resizeRowsToContents();

This makes the rows narrower but there is still a lot of padding between each row, as you can see here:

    Table After resizeRowsToContents()

Looking at the documentation I found I could set the hight of each row with:

table->verticalHeader()->setDefaultSectionSize(16);  

This removes the padding and gives me the tight spacing I want:

    Table After setDefaultSectionSize(16)

However, I'm concerned about using an absolute size in pixels. If the the system font is set to something large the text might not fit in the row.

Is there a way to remove the padding between rows while ensuring the text will always fit?

1

1 Answers

0
votes

Use a custom delegate with the QAbstractItemDelegate::sizeHint() method implemented in a way that it will return a correct size according to the font used.

To compute a correct height, you can use a QFontMetrics provided with the option parameter of the sizeHint() method.

int height = option.fontMetrics.height();

or more precisely

int height = option.fontMetrics.boundingRect(index.data().toString()).height();

EDIT: How to use a delegate:

CMyDelegate* delegate = new CMyDelegate(tableView);
tableView->setItemDelegate(delegate);