Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
684 views
in Technique[技术] by (71.8m points)

python - QFileDialog view folders and files but select folders only?

I'm creating my own custom file dialog using the following code:

file_dialog = QtGui.QFileDialog()
file_dialog.setFileMode(QtGui.QFileDialog.Directory)
file_dialog.setViewMode(QtGui.QFileDialog.Detail)
file_dialog.setOption(QtGui.QFileDialog.DontUseNativeDialog, True)

The behaviour that i'm interested in is for the user to be able to view both files and folders, but select folders only. (making files unselectable). Is that possible?

Note: Using the DirectoryOnly option is not good for me since it doesn't allow you to view files, just folders.

Edit (extra code that i forgot to add which responsible for being able to select multiple folders instead of just one):

file_view = file_dialog.findChild(QtGui.QListView, 'listView')
if file_view:
    file_view.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)
f_tree_view = file_dialog.findChild(QtGui.QTreeView)
if f_tree_view:
    f_tree_view.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To prevent files being selected, you can install a proxy model which manipulates the flags for items in the file-view:

dialog = QFileDialog()
dialog.setFileMode(QFileDialog.Directory)
dialog.setOption(QFileDialog.DontUseNativeDialog, True)

class ProxyModel(QIdentityProxyModel):
    def flags(self, index):
        flags = super(ProxyModel, self).flags(index)
        if not self.sourceModel().isDir(index):
            flags &= ~Qt.ItemIsSelectable
            # or disable all files
            # flags &= ~Qt.ItemIsEnabled
        return flags

proxy = ProxyModel(dialog)
dialog.setProxyModel(proxy)

dialog.exec()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...