66

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?

2 Answers 2

120

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 Oct 23, 2018 at 12:38
  • 1
    self is your parent QWidget
    – fivef
    Jul 25, 2019 at 7:21
  • from PySide2.QtWidgets import QFileDialog 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")) Aug 4, 2020 at 5:53
22

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
    May 7, 2021 at 7:30
  • what if I want either directory or file?
    – Wor Chan
    Aug 18, 2022 at 15:28

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

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