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模式,項目一次性排列完,這樣能確保滾動條的准確性,但會犧牲性能。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM