pythonpyqtpyside2qfiledialogqtwidgets

How to open only the directories with QFileDialog


This is my code :

    def open(self):
        file_dialog = QtWidgets.QFileDialog(self)
        file_dialog.setMimeTypeFilters(["dir"])

I want to open only the directories, I use the setMimeTypeFilters method, it works well when I set parameters like "image/jpeg" or "video/mp4".


Solution

  • There's actually a method built into QFileDialog that simplifies the process of getting directories called getExistingDirectory(). Common usage would look something like:

    directory = QtWidgets.QFileDialog.getExistingDirectory(caption='caption', directory='C:\\path\\to\\starting\\directory')
    

    It directly returns the selected directory as a string, or None if the dialog was cancelled. If you're looking for more control over your dialog, this may not be the best option. Otherwise, this makes the process quite straightforward.