69

In PyQt, how does one display a file browser that shows and selects only directories (not files)?

And how does one retrieve the name of the selected directory?

3 Answers 3

123

From inside your QDialog/QWidget class, you should be able to do:

file = str(QFileDialog.getExistingDirectory(self, "Select Directory"))
4
  • 9
    from PyQt5.QtWidgets import QFileDialog Commented Oct 23, 2018 at 12:38
  • 1
    self is your parent QWidget
    – fivef
    Commented Jul 25, 2019 at 7:21
  • from PySide2.QtWidgets import QFileDialog Commented Apr 17, 2020 at 20:44
  • 2
    If the above isn't working for you. It's the issue with your widget. pass None instead of self and it will work, like this: folder = str(QFileDialog.getExistingDirectory(None, "Select Directory")) Commented Aug 4, 2020 at 5:53
23

Just as simple as that:

folderpath = QtWidgets.QFileDialog.getExistingDirectory(self, 'Select Folder')

Here, self represents the parent window usually the QMainWindow object.

Similarly for File dialog:

filepath = QtWidgets.QFileDialog.getOpenFileName(self, 'Hey! Select a File')
2
  • up voted!!! very well explained and compared with the QtWidgets.QFileDialog.getOpenFileName(self, 'Hey! Select a File')
    – Ice Bear
    Commented May 7, 2021 at 7:30
  • what if I want either directory or file?
    – Wor Chan
    Commented Aug 18, 2022 at 15:28
0

In PyQt6 QFileDialog.getExistingDirectory is the same as PyQt5, but things change for QFileDialog.getOpenFileName which returns a tuple instead:

from PyQt6.QtWidgets import QFileDialog
file_path, filter_ = QFileDialog.getOpenFileName(self, 'Pick a file')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.