赞助

Qt QListView scrollTo定位指定项 和 LayoutMode布局的简单用法

工作中没有小事:点石成金,滴水成河,只有认真对待自己所做的一切事情,才能克服万难,取得成功。

项目开发中遇到一个问题,使用Qt 的QListView 加载目录,显示文件夹和文件信息,想在加载某个目录的时候定位到具体某一项,数据少的时候还好当前视口就能显示全,数据多了的时候,当前视口显示不全,碰巧选中那个不在当前视口,就想实现当前选中项显示在当前视口,那就得人为滑动滚动条。

QListView 是从QAbstractItemView派生的,他里面有个scrollTo函数确保指定项在当前视口可见:

Constant                                     Value                    Description
QAbstractItemView::EnsureVisible               0                      Scroll to ensure that the item is visible.

QAbstractItemView::PositionAtTop               1                      Scroll to position the item at the top of the viewport.

QAbstractItemView::PositionAtBottom            2                      Scroll to position the item at the bottom of the viewport.

QAbstractItemView::PositionAtCenter            3                      Scroll to position the item at the center of the viewport.


void QAbstractItemView::scrollTo(const QModelIndex &index, QAbstractItemView::ScrollHint hint = EnsureVisible);

这样就解决问题了

补充:QListView布局有时候会影响这个函数的结果,setLayoutMode(QListView::LayoutMode mode),这个mode有两个值Batched和SinglePass。默认是SinglePass。

1.当Batched(批处理)时,则在批处理项目的同时还可以处理事件,这样,便可以即时查看可见项目并与其交互,而其他项目还在不居中,这中模式下 每次批处理项目默认是100,可以通过函数setBatchSiz进行修改。

 如果在数据多的时候选择这个比较合适,类似分页显示,这个时候在scrollTo就有可能定位不到你想要的结果。

 

2.SinglePass模式,项目一次性排列完,这样能确保滚动条的准确性,但会牺牲性能。

posted @ 2021-11-11 22:29  车臣  阅读(898)  评论(0编辑  收藏  举报