PyQt - QFileDialog - directly browse to a folder?
Use getExistingDirectory
method instead:
from PyQt5.QtWidgets import QFileDialog
dialog = QFileDialog()
foo_dir = dialog.getExistingDirectory(self, 'Select an awesome directory')
print(foo_dir)
Here's a convenience function for quickly making an open/save QFileDialog
.
from PyQt5.QtWidgets import QFileDialog, QDialog
from definitions import ROOT_DIR
from PyQt5 import QtCore
def FileDialog(directory='', forOpen=True, fmt='', isFolder=False):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
options |= QFileDialog.DontUseCustomDirectoryIcons
dialog = QFileDialog()
dialog.setOptions(options)
dialog.setFilter(dialog.filter() | QtCore.QDir.Hidden)
# ARE WE TALKING ABOUT FILES OR FOLDERS
if isFolder:
dialog.setFileMode(QFileDialog.DirectoryOnly)
else:
dialog.setFileMode(QFileDialog.AnyFile)
# OPENING OR SAVING
dialog.setAcceptMode(QFileDialog.AcceptOpen) if forOpen else dialog.setAcceptMode(QFileDialog.AcceptSave)
# SET FORMAT, IF SPECIFIED
if fmt != '' and isFolder is False:
dialog.setDefaultSuffix(fmt)
dialog.setNameFilters([f'{fmt} (*.{fmt})'])
# SET THE STARTING DIRECTORY
if directory != '':
dialog.setDirectory(str(directory))
else:
dialog.setDirectory(str(ROOT_DIR))
if dialog.exec_() == QDialog.Accepted:
path = dialog.selectedFiles()[0] # returns a list
return path
else:
return ''
If you use the static QFileDialog
functions, you'll get a native file-dialog, and so you'll be limited to the functionality provided by the platform. You can consult the documentation for your platform to see if the functionality you want is available.
If it's not available, you'll have to settle for Qt's built-in file-dialog, and add your own features. For your specific use-case, this should be easy, because the built-in dialog already seems to have what you want. It has a side-bar that shows a list of "Places" that the user can navigate to directly. You can set your own places like this:
dialog = QtGui.QFileDialog(self, 'Audio Files', directory, filter)
dialog.setFileMode(QtGui.QFileDialog.DirectoryOnly)
dialog.setSidebarUrls([QtCore.QUrl.fromLocalFile(place)])
if dialog.exec_() == QtGui.QDialog.Accepted:
self._audio_file = dialog.selectedFiles()[0]