Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QTreeView::scrollTo not working

Tags:

c++

qt

Qt 4.8

I have a QTreeView based class with an asociated QAbstractItemModel based class. If I reload the model with new information I want to expand/scroll the tree to a previous selected item.

Both clases, tree view and model are correctly created and connected using QTreeView::setSelectionModel(...) working everything properly.

After reloading the model, I get a valid index to the previous selected item and I scrollTo it:

myTreeView->scrollTo(index);

but the tree is not expanded. However, if I expand the tree manually, the item is really selected.

Tree view is initialized in contruct with:

header()->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);
header()->setStretchLastSection(false);
header()->setResizeMode(0, QHeaderView::ResizeToContents);

Any idea about expanding the tree to the selection?

like image 523
Tio Pepe Avatar asked Feb 17 '23 00:02

Tio Pepe


1 Answers

Even QTreeView::scrollTo documentation says:

Scroll the contents of the tree view until the given model item index is 
visible. The hint parameter specifies more precisely where the item should 
be located after the operation. If any of the parents of the model item 
are collapsed, they will be expanded to ensure that the model item is visible.

That is not really true (I think)

If solved the problem expanding all previous tree levels manually:

// This slot is invoqued from model using last selected item
void MyTreeWidget::ItemSelectedManually(const QModelIndex & ar_index)
{
    std::vector<std::pair<int, int> > indexes;

    // first of all, I save all item "offsets" relative to its parent

    QModelIndex indexAbobe = ar_index.parent();
    while (indexAbobe.isValid())
    {
        indexes.push_back(std::make_pair(indexAbobe.row(), indexAbobe.column()));
        indexAbobe = indexAbobe.parent();
    }

    // now, select actual selection model

    auto model = _viewer.selectionModel()->model();

    // get root item

    QModelIndex index = model->index(0, 0, QModelIndex());
    if (index.isValid())
    {
        // now, expand all items below

        for (auto it = indexes.rbegin(); it != indexes.rend() && index.isValid(); ++it)
        {
            auto row = (*it).first;
            auto colum = (*it).second;

            _viewer.setExpanded(index, true);

            // and get a new item relative to parent
            index = model->index(row, colum, index);
        }
    }

    // finally, scroll to real item, after expanding everything above.
    _viewer.scrollTo(ar_index);
}
like image 127
Tio Pepe Avatar answered Feb 28 '23 09:02

Tio Pepe