QTreeWidget and QScrollArea
-
Hi,
I'm trying to create a QTreeWidget that does not allow for scrolling. Basically what I need is that the frame of the widget is the same size of the contents of the tree. So if you expand the tree, the frame should become bigger. By default, the frame stays the same and a scroll bar is added.
(I would like to have this because I have a ScrollArea that contains one QTreeWidget with multiple other widgets in a QVBoxLayout. I would like 1 vertical scrollbar for the tree and all the other widgets at the same time, not one for the tree widget and one for the parent scroll area.)
How would I go about doing this??
-
You can disable scrolling by calling
@
QAbstractScrollArea::setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
QAbstractScrollArea::setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
@Then the scrollbars are gone. But you have to resize the view by yout own I think.
-
Thanx Gerolf, that idea worked. Had to connect to the signals itemExpanded and itemCollapsed to calculate the size. Here is an example of the recursive function to calculate the needed height.
@
void myTreeWidget::CalculateHeight()
{
int h = 0;int topLevelCount = topLevelItemCount(); for(int i = 0;i < topLevelCount;i++) { QTreeWidgetItem * item = topLevelItem(i); h += CalculateHeightRec(item); } if(h != 0) { h += header()->sizeHint().height(); setMinimumHeight(h); }
}
int myTreeWidget::CalculateHeightRec(QTreeWidgetItem * item)
{
if(!item)
return 0;QModelIndex index = indexFromItem(item); if(!item->isExpanded()) { return rowHeight(index); } int h = item->sizeHint(0).height() + 2; int childCount = item->childCount(); for(int i = 0; i < childCount;i++) { h += CalculateHeightRec(item->child(i)); } return h;
}
@
-
If you set the scroll mode to QAbstractItemView::ScrollPerPixel (see "setHorizontalScrollMode() ":http://doc.qt.nokia.com/latest/qabstractitemview.html#horizontalScrollMode-prop for details) you might get the treeviews contents height (without the border and the headers) from "QScrollBar::maximum() ":http://doc.qt.nokia.com/latest/qabstractslider.html#maximum-prop. The scrollbar maxium is calculated even if the scrollbar policy "always off". That might save you some extra calculations.
-
adding just a note: Volker's solution is more rational but not works. steno's did
-
I tried the solution of steno of calculating the height and setting the minimumHeight. My problem there is that the item-sizeHint (0).height() returns -1?
Any idea why that is?
-
since Qt 5.2 this is much easier to do:
view->setSizeAdjustPolicy(QAbstractScrollArea::AdjustToContents);
-
That works perfect. Thanks a lot!