How can I get rid of the white space outside the cells of my table?

If you don’t need all of your header sections to be resizable, then you can achieve this by setting the resizeMode [qt.nokia.com] to stretch for one or more of the header sections:

  1. table->horizontalHeader()->setResizeMode(4, QHeaderView::Stretch);

If you do need all of your header sections to be resizeable, then you need to reimplement the sizeHint() [qt.nokia.com] to account for the size of the cells and headers in the table.

Then you need to set this size to be the maximum size of the table. Since you allow resizing of the table’s columns, you also need to connect a slot to the sectionResized [doc.qt.nokia.com] signal and call setMaximumSize(sizeHint()) in there.

The example below demonstrates how this can be done for a toplevel table. If you need this to work for a table that is embedded into another widget, then you need to set the sizePolicy [doc.qt.nokia.com] to fixed, so that the sizeHint() is the only alternative.

  1.     #include <QtGui>
  2.  
  3.     class TableWidget : public QTableWidget
  4.     {
  5.      Q_OBJECT
  6.     public:
  7.      TableWidget(int rows, int columns) : QTableWidget(rows, columns)
  8.      {
  9.       connect(horizontalHeader(), SIGNAL(sectionResized(int, int, int)), this, SLOT(sectionResized()));
  10.       connect(verticalHeader(), SIGNAL(sectionResized(int, int, int)), this, SLOT(sectionResized()));
  11.      }
  12.  
  13.      QSize sizeHint () const
  14.      {
  15.       int newWidth = 0;
  16.       int newHeight =0;
  17.       for (int i = 0; i < columnCount(); i++) {
  18.        newWidth+= columnWidth(i);
  19.       }
  20.       for (int y = 0; y < rowCount(); y++) {
  21.        newHeight+= rowHeight(y);
  22.       }
  23.       newWidth+=verticalHeader()->width() + 2 *frameWidth();
  24.              newHeight+= horizontalHeader()->height() +2 *frameWidth();
  25.              return QSize(newWidth, newHeight);
  26.      }
  27.  
  28.     public slots:
  29.      void sectionResized()
  30.      {
  31.       setMaximumSize(sizeHint());
  32.      }
  33.     };
  34.  
  35.    #include "main.moc"
  36.  
  37.    int main(int argc, char **argv)
  38.     {
  39.      QApplication app(argc, argv);
  40.      TableWidget table(10,10);
  41.      table.setMaximumSize(table.sizeHint());
  42.      table.show();
  43.      table.resize(table.sizeHint());
  44.      return app.exec();
  45.     }
  46.  

1 comment

December 15, 2010

Picture of Exodus Exodus

Lab Rat

I’ve been looking for this for a while now on Google. Qt Dev Net rocks!

Write a comment

Sorry, you must be logged in to post a comment.