Search code examples
qtdelegatesqtablewidgetqtreewidget

How to autofit widget size and position to a cell in QTreeWidget?


I pragrammaticaly create a QTreeWidget.

Then I pragrammaticaly add some items.

Then I add two QLabel widgets to two items (QTreeWidgetItem) by

myTree->setItemWidget(item1, 0, myLabel1);
myTree->setItemWidget(item2, 0, myLabel2);

And then I try to resize the row of the item pragrammaticaly. If I use an

item1->setSizeHint(0, QSize(myWidth, myHeight) );

the row chaged. But myLabel1 is not.

If I use an

item1->setSizeHint(0, QSize(myWidth, myHeight) );
myLabel->resize(myWidth, myHeight);

everething is ok but the row of myLabel2 mis adjusting to label by position.

Can I do something to auto-adjusting a widget (by size and position) to a cell of QTreeWidget?

P.S. After any resizing of tree (resize by width or expand/collapse node) widgets updates correctly.


Solution

  • In view of the fact that autofit start after resizing QTreeWidget, there is some method inside that resize widgets in cells. So I opened QTreeWidget description (https://doc.qt.io/qt-5/qtreewidget.html) and red all of Public Functions and Public Slots. When I did not find any useful function I looked at a parent class (QTreeView). And found

    myTree->resizeColumnToContent(0);
    

    Call resizeColumnToContent after resizing any row in a QTreeWidget and widgets will be always fit to cells.

    P.S. I am the OP.