PyQt QFileDialog

Summary: in this tutorial, you’ll learn how to use the PyQt QFileDialog class to create file dialogs that allow users to select files or directories from the file system.

Introduction to the PyQt QFileDialog

The QFileDialog class creates a file dialog widget that allows users to traverse the file system and select one or more files or a directory.

To create a file dialog object, you create a new instance of the QFileDialog:

dialog = QFileDialog(self)Code language: Python (python)

The QFileDialog object has the setFileMode() method that allows users to select an existing file:

dialog.setFileMode(QFileDialog.FileMode.ExistingFiles)Code language: Python (python)

or a file that does not exist:

dialog.setFileMode(QFileDialog.FileMode.AnyFile)Code language: Python (python)

This option is useful for the Save As file dialog scenario. See the QFileDialog.FileMode enum for the complete file modes.

Filtering file types

To specify which types of files users are expected to select, you can use the setNameFilter() method. For example, the following filter expects users to select only PNG and JPEG files:

dialog.setNameFilter("Images (*.png *.jpg)")Code language: Python (python)

To use multiple filters, you need to separate each with two semicolons. For example:

"Images (*.png  *.jpg);;Vector (*.svg)"Code language: Python (python)

Setting views for file dialogs

The file dialog has two view modes: list and detail.

  • The list view shows the contents of the current directory as a list of files and directory names
  • The detail view displays additional information such as file sizes and modified dates.

To set the view mode, you use the setViewMode() method:

dialog.setViewMode(QFileDialog.Detail)Code language: Python (python)

Once you complete the setting, you can show the file dialog using the selectFiles() method. If the user clicks the OK button, the selected files are put in fileNames:

if dialog.exec_():
    fileNames = dialog.selectedFiles()Code language: Python (python)

To set starting directory of the file dialog, you use the setDirectory() method. For example:

dialog.setDirectory('C:/images/')Code language: Python (python)

The following program uses a file dialog that allows users to select image files:

import sys
from PyQt6.QtWidgets import (
    QApplication, 
    QWidget, 
    QFileDialog, 
    QGridLayout,
    QPushButton, 
    QLabel,
    QListWidget
)
from pathlib import Path


class MainWindow(QWidget):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.setWindowTitle('PyQt File Dialog')
        self.setGeometry(100, 100, 300, 150)

        layout = QGridLayout()
        self.setLayout(layout)

        # file selection
        file_browser_btn = QPushButton('Browse')
        file_browser_btn.clicked.connect(self.open_file_dialog)

        self.file_list = QListWidget(self)

        layout.addWidget(QLabel('Files:'), 0, 0)
        layout.addWidget(self.file_list, 1, 0)
        layout.addWidget(file_browser_btn, 2 ,0)

        self.show()

    def open_file_dialog(self):
        dialog = QFileDialog(self)
        dialog.setDirectory(r'C:\images')
        dialog.setFileMode(QFileDialog.FileMode.ExistingFiles)
        dialog.setNameFilter("Images (*.png *.jpg)")
        dialog.setViewMode(QFileDialog.ViewMode.List)
        if dialog.exec():
            filenames = dialog.selectedFiles()
            if filenames:
                self.file_list.addItems([str(Path(filename)) for filename in filenames])


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec())Code language: Python (python)

Selecting a single file using the getOpenFileName() method

It’s more concise to use the static method getOpenFileName() of the QFileDialog class to open file dialog. For example:

import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QFileDialog, QWidget, QGridLayout,QLineEdit,QPushButton, QLabel
from pathlib import Path

class MainWindow(QWidget):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.setWindowTitle('PyQt File Dialog')
        self.setGeometry(100, 100, 400, 100)

        layout = QGridLayout()
        self.setLayout(layout)

        # file selection
        file_browse = QPushButton('Browse')
        file_browse.clicked.connect(self.open_file_dialog)
        self.filename_edit = QLineEdit()

        layout.addWidget(QLabel('File:'), 0, 0)
        layout.addWidget(self.filename_edit, 0, 1)
        layout.addWidget(file_browse, 0 ,2)

      
        self.show()


    def open_file_dialog(self):
        filename, ok = QFileDialog.getOpenFileName(
            self,
            "Select a File", 
            "D:\\icons\\avatar\\", 
            "Images (*.png *.jpg)"
        )
        if filename:
            path = Path(filename)
            self.filename_edit.setText(str(path))


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec())Code language: Python (python)

Output:

How it works.

First, create a button and connect the clicked signal with the open_file_dialog method:

file_browse = QPushButton('Browse')
file_browse.clicked.connect(self.open_file_dialog)Code language: Python (python)

Second, define the open_file_dialog() method and call the getOpenFileName() static method of the QFileDialog class to open a file dialog:

def open_file_dialog(self):
    filename, _ = QFileDialog.getOpenFileName(
        self,
        "Select a File",
        r"C:\images\",
        "Images (*.png *.jpg)"
    )
    if filename:
        path = Path(filename)
        self.filename_edit.setText(str(path))Code language: Python (python)

The getOpenFileName() has the title of “Select a File”, starting directory as “C:\images\”, and expects users to select a png or jpg file only.

The getOpenFileName() method returns a tuple. The first element of the tuple stores the selected file path. Since we don’t need the second element, we assign it to the _ variable.

Selecting multiple files using the getOpenFileNames() method

To allow users to select multiple files in a file dialog, you use the getOpenFileNames() method instead of the getOpenFileName() method.

The getOpenFileNames() works like the getOpenFileName() except the first element of the returned tuple contains a list of the selected files.

The following program uses the getOpenFileNames() method to allow users to select multiple files and fills a list widget with selected file names:

import sys
from PyQt6.QtWidgets import QApplication,  QFileDialog, QWidget, QGridLayout, QListWidget, QPushButton, QLabel
from pathlib import Path


class MainWindow(QWidget):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.setWindowTitle('PyQt File Dialog')
        self.setGeometry(100, 100, 400, 100)

        layout = QGridLayout()
        self.setLayout(layout)

        # file selection
        file_browse = QPushButton('Browse')
        file_browse.clicked.connect(self.open_file_dialog)

        self.file_list = QListWidget(self)

        layout.addWidget(QLabel('Selected Files:'), 0, 0)
        layout.addWidget(self.file_list, 1, 0)
        layout.addWidget(file_browse, 2, 0)

        self.show()

    def open_file_dialog(self):
        filenames, _ = QFileDialog.getOpenFileNames(
            self,
            "Select Files",
            r"C:\images\",
            "Images (*.png *.jpg)"
        )
        if filenames:
            self.file_list.addItems([str(Path(filename))
                                     for filename in filenames])


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec())Code language: Python (python)

Output:

Selecting a directory

To open a file dialog for selecting a directory, you use the getExistingDirectory() method of the QFileDialog class. For example:

import sys
from PyQt6.QtWidgets import QApplication,  QFileDialog, QWidget, QGridLayout, QLineEdit, QPushButton, QLabel
from pathlib import Path


class MainWindow(QWidget):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.setWindowTitle('PyQt File Dialog')
        self.setGeometry(100, 100, 400, 100)

        layout = QGridLayout()
        self.setLayout(layout)

        # directory selection
        dir_btn = QPushButton('Browse')
        dir_btn.clicked.connect(self.open_dir_dialog)
        self.dir_name_edit = QLineEdit()

        layout.addWidget(QLabel('Directory:'), 1, 0)
        layout.addWidget(self.dir_name_edit, 1, 1)
        layout.addWidget(dir_btn, 1, 2)

        self.show()

    def open_dir_dialog(self):
        dir_name = QFileDialog.getExistingDirectory(self, "Select a Directory")
        if dir_name:
            path = Path(dir_name)
            self.dir_name_edit.setText(str(path))


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec())Code language: Python (python)

Output:

Summary

  • A file dialog allows you to select one or more files or a directory.
  • Use the QFileDialog class to create a file dialog widget.
  • Use the getOpenFileName() static method of the QFileDialog to create a file dialog that allows users to select a single file.
  • Use the getOpenFileNames() static method of the QFileDialog class to create a file dialog that allows users to select multiple files.
  • Use the getExistingDirectory() static method of the QFileDialog class to create a file dialog that allows users to select a directory.
Did you find this tutorial helpful ?