how to have a directory dialog
Asked Answered
E

3

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?

Exculpate answered 26/11, 2010 at 14:19 Comment(0)
D
122

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

file = str(QFileDialog.getExistingDirectory(self, "Select Directory"))
Dual answered 26/11, 2010 at 14:28 Comment(4)
from PyQt5.QtWidgets import QFileDialogMelindamelinde
self is your parent QWidgetHoldall
from PySide2.QtWidgets import QFileDialogUnconscious
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"))Exchange
B
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')
Beaverbrook answered 13/2, 2021 at 20:8 Comment(2)
up voted!!! very well explained and compared with the QtWidgets.QFileDialog.getOpenFileName(self, 'Hey! Select a File')Mylo
what if I want either directory or file?Mme
M
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')
Monzonite answered 26/12, 2023 at 9:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.