2010-07-09 255 views
4

我需要顯示一個特定目錄的QTreeView,並且我想讓用戶有可能用RegExp過濾這些文件。QTreeView,QFileSystemModel,setRootPath和QSortFilterProxyModel用RegExp進行過濾

據我所知Qt文檔我可以在標題這樣提到的類實現這一點:

// Create the Models 
QFileSystemModel *fileSystemModel = new QFileSystemModel(this); 
QSortFilterProxyModel *proxyModel = new QSortFilterProxyModel(this); 

// Set the Root Path 
QModelIndex rootModelIndex = fileSystemModel->setRootPath("E:\\example"); 

// Assign the Model to the Proxy and the Proxy to the View 
proxyModel->setSourceModel(fileSystemModel); 
ui->fileSystemView->setModel(proxyModel); 

// Fix the TreeView on the Root Path of the Model 
ui->fileSystemView->setRootIndex(proxyModel->mapFromSource(rootModelIndex)); 

// Set the RegExp when the user enters it 
connect(ui->nameFilterLineEdit, SIGNAL(textChanged(QString)), 
     proxyModel, SLOT(setFilterRegExp(QString))); 

當開始該程序的樹視圖被正確地固定在指定的目錄。但只要用戶更改RegExp,它就像TreeView忘記RootIndex一樣。刪除RegExp LineEdit中的所有文本(或輸入RegExp,如「。」)後,它再次顯示所有目錄(在Windows上,這意味着所有驅動器等)

我在做什麼錯? :/

回答

9

我從Qt的郵件列表,它解釋了這個問題的迴應:

我認爲正在發生的事情,是因爲 一旦你開始過濾時, 索引你爲你的根使用沒有 更長的存在。該視圖然後重置爲 作爲根索引的無效索引。 這個過濾在整個 模型樹上工作,而不僅僅是你在 看到你是否開始進入你的過濾器的部分!

我想你將需要一個 修改代理模型來做你想要的東西 。它應該只對 路徑下的項目應用 篩選,但只允許根路徑本身 (以及其他任何項目)。

因此,在功能filterAcceptsRow()中檢查子類QSortFilterProxyModel和一些parent()檢查後,現在按預期工作!

+0

你有沒有可能分享你所做的修改?我現在遇到了這個確切的問題,但我不知道如何解決它。 – 2011-04-19 22:13:56

+0

很遺憾,我無法再訪問此項目。這是郵件列表線程:http://www.mentby.com/Group/qt-interest/qtreeview-qfilesystemmodel-setrootpath-and-qsortfilterproxymodel-with-regexp-for-filtering.html – Strayer 2011-05-23 19:44:09

3

我通過Google發現了這個問題,並根據此線程(以及其他Google搜索結果)制定瞭解決方案。你可以找到我的解決辦法:

https://github.com/ghutchis/avogadro/blob/testing/libavogadro/src/extensions/sortfiltertreeproxymodel.h

https://github.com/ghutchis/avogadro/blob/testing/libavogadro/src/extensions/sortfiltertreeproxymodel.cpp

有一件事你必須記住(這不是這裏所說)是子行不能由QFileSystemModel自動獲取,所以你必須調用fetchMore()在它們上面。就我而言,我們只有一層子目錄,所以它相當容易。

如果您的代碼想要處理更多不同的目錄層次結構,則需要將filterAcceptsRow()底部附近的for()循環更改爲遞歸。

相關問題