QFileDialog があり、~/Documents にないすべてのパスを除外したいと考えています。
現在持っている
from PyQt5 import QtCore
import os
...
dialog = QtWidgets.QFileDialog(...)
dialog.setDirectory(os.path.expanduser("~/Documents"))
dialog.setProxyModel(MyFilter())
selectedPath = dialog.exec_()
...
class MyFilter(QtCore.QSortFilterProxyModel):
def filterAcceptsRow(self, p_int, QModelIndex):
sourceModel = self.sourceModel()
index = sourceModel.index(p_int, 0,QModelIndex)
path = sourceModel.filePath(index)
return self._inside_documents_or_is_ancestor(path)
def _inside_documents_or_is_ancestor(self, path):
docpath = os.path.expanduser("~/Documents")
if path.startswith(docpath) or docpath.startswith(path):
print True, path, docpath
return True
return False
QFileDialogでファイルシステム内の任意のファイルを選択できるため、パスがフィルタリングされていないようです。
filterAcceptsRow() の詳細についてはわかりませんが、ディレクトリを拒否すると、そのサブディレクトリは考慮されないようです。そのため、目的のパスの先祖であるパスを受け入れています。
私はpyqt 5.1とpython 2.7.5を実行しています