QTreeView::scrollTo 不起作用

Tio*_*epe 4 c++ qt

Qt 4.8

我有一个QTreeView基础课程和一个相关的QAbstractItemModel基础课程。如果我使用新信息重新加载模型,我想将树展开/滚动到先前选定的项目。

QTreeView::setSelectionModel(...)使用一切正常工作,可以正确创建和连接两个类、树视图和模型。

重新加载模型后,我获得了上一个所选项目的有效索引,然后滚动到它:

myTreeView->scrollTo(index);
Run Code Online (Sandbox Code Playgroud)

但树没有扩展。但是,如果我手动展开树,则该项目确实被选中。

树视图的初始化结构如下:

header()->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);
header()->setStretchLastSection(false);
header()->setResizeMode(0, QHeaderView::ResizeToContents);
Run Code Online (Sandbox Code Playgroud)

关于将树扩展到选择的任何想法吗?

Tio*_*epe 5

甚至QTreeView::scrollTo文档也说:

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.
Run Code Online (Sandbox Code Playgroud)

这不是真的(我认为)

如果解决了手动扩展所有先前树级别的问题:

// 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);
}
Run Code Online (Sandbox Code Playgroud)