QFileDialog that accepts a single file or a single directory

前端 未结 4 1367
有刺的猬
有刺的猬 2021-02-13 23:46

Is it possible to show a QFileDialog where the user can select a file or a directory, either one?

QFileDialog::getOpenFileName() accepts only files, while

4条回答
  •  无人共我
    2021-02-14 00:26

    Connect to the currentChanged signal and then set the file mode to the currently selected item (directory or file). This is a Python3 implementation:

    class GroupFileObjectDialog(QFileDialog):
    
        def __init__(self, parent):
            super().__init__(parent)
            self.setOption(QFileDialog.DontUseNativeDialog)
            self.setFileMode(QFileDialog.Directory)
            self.currentChanged.connect(self._selected)
    
        def _selected(self,name):
            if os.path.isdir(name):
                self.setFileMode(QFileDialog.Directory)
            else:
                self.setFileMode(QFileDialog.ExistingFile)
    

    Tested on PyQt 5.14 running on linux / Ubuntu18.04.

提交回复
热议问题