PDA

View Full Version : [QTreeView] Fit to height



Auliyaa
4th March 2015, 14:41
Hi all,

I'm currently working on a GUI where multiple QTreeView are put into a single, parent QScrollArea.
Since a QTreeView inherits from QAbstractScrollArea, and in order to avoid showing multiple scroll bars, I'm looking to resize my QTreeView so that its height fits with its content.

I've found no solution so far that gives me the precise height I should set on my QTreeView so that no scrollbar is needed. Here is the solution that comes the closest to the result:


QModelIndex MyClass::lastIndex(QAbstractItemModel *model, const QModelIndex &parent) const
{
// No more children => The parent is the last item
if (model->rowCount(parent) == 0) return parent;
QModelIndex lastChild = model->index(model->rowCount(parent)-1,0,parent);
return lastIndex(model,lastChild);
}

int MyClass::treeViewHeight() const
{
QRect r = _treeView->visualRect(lastIndex(_treeView->model(),_treeView->rootIndex()));
return r.y()+r.height();
}

So basically I check for the visual rect of the last item in my model and try to resize the treeview accordingly. However, I still end up with one ore more rows (depending on the total number of items) that are not shown in the viewport.

Any help would be greatly appreciated ^^

Santosh Reddy
4th March 2015, 15:34
You have count the visible items and add each items height then viewport margin, then set that height to treeview.

height = sum of height of all visible items (both child, sub-child... etc) + viewport margin (couple of pixels)