2011-03-19 65 views
2

我正在處理一個需要在樹視圖中顯示某些文件夾的項目。我有喜歡完整的文件路徑列表:PYQT文件路徑樹

  • C:\文件夾1 \文件1
  • C:\文件夾1 \ folder11 \文件2
  • C:\文件夾2 \文件3

那麼文件路徑實際上存儲在我通過運行查詢獲得的sql服務器。

我正在尋找一種方式將它放到QTreeView中。

我嘗試過使用QFileSystemModel並使用setNameFilters,但這不起作用,因爲您無法將路徑輸入到過濾器中。

有人建議使用QSortFilterProxyModel,但我不知道如何做到這一點。

謝謝。

湯姆。

回答

1

PLS,看看下面的例子會爲你工作:

import sys 
from PyQt4 import QtGui, QtCore 

class TestSortFilterProxyModel(QtGui.QSortFilterProxyModel): 
    def __init__(self, parent=None): 
     super(TestSortFilterProxyModel, self).__init__(parent) 
     self.filter = ['folder0/file0', 'folder1/file1']; 

    def filterAcceptsRow(self, source_row, source_parent): 
     index0 = self.sourceModel().index(source_row, 0, source_parent) 
     filePath = self.sourceModel().filePath(index0) 

     for folder in self.filter: 
      if filePath.startsWith(folder) or QtCore.QString(folder).startsWith(filePath): 
       return True;   
     return False  

class MainForm(QtGui.QMainWindow): 
    def __init__(self, parent=None): 
     super(MainForm, self).__init__(parent) 

     model = QtGui.QFileSystemModel(self) 
     model.setRootPath(QtCore.QDir.currentPath()) 

     proxy = TestSortFilterProxyModel(self) 
     proxy.setSourceModel(model)  

     self.view = QtGui.QTreeView() 
     self.view.setModel(proxy) 

     self.setCentralWidget(self.view) 

def main(): 
    app = QtGui.QApplication(sys.argv) 
    form = MainForm() 
    form.show() 
    app.exec_() 

if __name__ == '__main__': 
    main() 

希望這會有所幫助,至於

+0

感謝您的答覆可悲的是,當我運行此我只是得到一個空的小部件。當前路徑是「D:\ Test」,在那裏有兩個文件夾folder0和folder1與相應的文件匹配你的過濾器,但仍然沒有。 – supertom44 2011-03-19 18:56:05

+0

這個例子在我的ubuntu上運行得很好,過濾模型中的邏輯非常基本,只是爲了給你一個關於如何處理你的任務的想法。跟蹤filterAcceptsRow方法並將其調整爲任何過濾規則。 – 2011-03-19 19:39:54

+0

我設法讓它工作我意識到這是由於我沒有使用完整的文件路徑,一旦我重新讀取文件,並意識到它使用開始,我意識到它需要是完整的文件路徑。謝謝 – supertom44 2011-03-19 20:28:09