Moayyad Yaghi
Moayyad Yaghi

Reputation: 3722

how to have a directory dialog

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?

Upvotes: 70

Views: 102746

Answers (3)

mascIT
mascIT

Reputation: 485

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')

Upvotes: 0

Ali Sajjad Rizavi
Ali Sajjad Rizavi

Reputation: 4480

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')

Upvotes: 23

TZHX
TZHX

Reputation: 5377

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

file = str(QFileDialog.getExistingDirectory(self, "Select Directory"))

Upvotes: 123

Related Questions