1. 程式人生 > 其它 >Qt QListView scrollTo定位指定項 和 LayoutMode佈局的簡單用法

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