Skip to content

Instantly share code, notes, and snippets.

@sneakers-the-rat
Created March 29, 2024 20:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sneakers-the-rat/22c3449e2c7043c594712bce89c27e8e to your computer and use it in GitHub Desktop.
Save sneakers-the-rat/22c3449e2c7043c594712bce89c27e8e to your computer and use it in GitHub Desktop.
Select multiple directories with PySide6
from pathlib import Path
from typing import Optional, List
from PySide6.QtWidgets import (
QApplication,
QFileDialog,
QListView,
QAbstractItemView,
QTreeView,
QFileSystemModel
)
def choose_directories(base:Path = Path('.')) -> Optional[List[str]]:
"""
Open a dialogue to select multiple directories
Args:
base (Path): Starting directory to show when opening dialogue
Returns:
List[str]: List of paths that were selected, ``None`` if "cancel" selected"
References:
Mildly adapted from https://stackoverflow.com/a/28548773
to use outside an exising Qt Application
"""
app = QApplication()
file_dialog = QFileDialog()
file_dialog.setOption(QFileDialog.Option.DontUseNativeDialog, True)
file_dialog.setFileMode(QFileDialog.Directory)
for widget_type in (QListView, QTreeView):
for view in file_dialog.findChildren(widget_type):
if isinstance(view.model(), QFileSystemModel):
view.setSelectionMode(
QAbstractItemView.ExtendedSelection)
if file_dialog.exec():
paths = file_dialog.selectedFiles()
return paths
if __name__ == "__main__":
paths = choose_directories()
print(paths)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment