QTableWidget: How can I get tighter lines with less vertical spacing padding?

What you're looking for has a very silly solution IMHO, but it works. You need to set the headers' defaultSectionSize() members. Accessed via verticalHeader() & horizontalHeader(). I never really set the column width's w/ this b/c most of my projects involve me adding rows, not columns, and I just call resizeColumnsToContents or do a manual resizing. However, the rows is irksome. I generally get the height of the font using QFontMetrics, and add 2. Any subsequent row added should have this height, and viola: tighter look.

Hope that helps.

EDIT:

Untested code:

QFontMetrics fm( my_font );
int h = fm.height() + 2;
my_table->verticalHeader()->setDefaultSectionSize( h );

The code getting 'h' might be unsound. It was just an example. Copy & paste the following rather rudimentary code. Change the value in "setDefaultSectionSize()", recompile, and run. You should see the difference. Setting this to 10 or 50 yields visible results. In the code above, it is possible QFontMetrics or QFont is messing something up.

You can use whatever you want to get the height, but font size makes the most sense.

#include <QtGui>

int main( int argc, char* argv[] )
{
 QApplication app( argc, argv );

 QDialog* my_dialog  = new QDialog();
 QHBoxLayout* layout  = new QHBoxLayout();
 QTableWidget* my_table_widget = new QTableWidget( my_dialog );

 my_table_widget->setRowCount( 10 );
 my_table_widget->setColumnCount( 10 );
 my_table_widget->verticalHeader()->setDefaultSectionSize( 15 );
 layout->addWidget( my_table_widget );
 my_dialog->setLayout( layout );
 my_dialog->resize( 500, 200 );
 my_dialog->show();

 return app.exec();
}

EDIT: I don't know how to format a block of code here... forgive me. :)

Edit 2: I fixed that, and the following simple tighterTable.pro file helps along.

TEMPLATE = app
TARGET =
DEPENDPATH += .
INCLUDEPATH += .

SOURCES += tighterTable.cpp    # if that is the filename

Thanks a big fat bunch for this. BTW: Editing as code is just indenting by four spaces, and/or hitting the button with the little '101010' in the formatting row.


QTableWidget is a convenience model and view. Typically, QAbstractItemModel's data() method provides a SizeHintRole that is used to tell the view what size each cell should be.

Since you're using QTableWidget, I don't think there's anything that you can do to change the size hint being returned by its internal model. Even the Qt style sheet documentation mentions nothing in that area.