64

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?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Moayyad Yaghi
  • 3,622
  • 13
  • 51
  • 67

2 Answers2

117

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

file = str(QFileDialog.getExistingDirectory(self, "Select Directory"))
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
TZHX
  • 5,291
  • 15
  • 47
  • 56
21

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')
Ali Sajjad
  • 3,589
  • 1
  • 28
  • 38