且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

QFileDialog查看文件夹和文件,但仅选择文件夹吗?

更新时间:2023-01-15 19:07:33

要防止选择文件,可以安装代理模型,该模型处理文件视图中项目的标志:

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()