I'm trying to get a QTreeWidget to show a text column and some equally sized checkbox columns. This eventually works, but the QTreeWidget seems hell-bent on showing up at 256x192 pixels, although the stuff put in it requires less space.

QWidget::adjustSize() claims to resize a widget to fit the contents, but does not.
Calling resize() on the QTreeWidget helps if it is a top level widget, but does nothing if it is in a layout together with other widgets.

It is possible to let the user manually adjust the size after it is rendered, but how does one resize a QTreeWidget to fit its contents from code? (Tested in Qt-4.2.0-rc1)

/Joakim Rosqvist


Qt Code:
  1. #include <QApplication>
  2. #include <QTreeWidget>
  3. #include <QHeaderView>
  4. #include <QHBoxLayout>
  5.  
  6. int main( int argc, char **argv )
  7. {
  8. QApplication app( argc, argv );
  9.  
  10. QWidget *hbox = new QWidget;
  11. hbox->setLayout(lay = new QHBoxLayout);
  12.  
  13. tw->setColumnCount(3);
  14. twi->setText(0,"Text");
  15. twi->setCheckState(1,Qt::Checked);
  16. twi->setCheckState(2,Qt::Checked);
  17. tw->addTopLevelItem(twi);
  18. tw->resizeColumnToContents(0);
  19. tw->resizeColumnToContents(1);
  20. tw->resizeColumnToContents(2);
  21. tw->header()->setResizeMode(0, QHeaderView::Interactive);
  22. tw->header()->setResizeMode(1, QHeaderView::ResizeToContents);
  23. tw->header()->setResizeMode(2, QHeaderView::ResizeToContents);
  24. tw->header()->setStretchLastSection(false);
  25.  
  26. tw->adjustSize(); // no effect!
  27. tw->resize(110,100); // no effect!
  28.  
  29. lay->addWidget(tw);
  30. hbox->show();
  31. app.exec();
  32. return 0;
  33. }
To copy to clipboard, switch view to plain text mode