In this blog post, we will explore how to use the QDirDialog
class in PyQt to create a directory selection dialog in Python applications. The QDirDialog
class allows users to select a directory from their file system.
Prerequisites
To follow along with the examples in this post, you should have a basic understanding of Python and PyQt. If you are new to PyQt, I recommend checking out the PyQt documentation or tutorial to get started.
Getting Started
First, let’s import the necessary PyQt classes and modules:
from PyQt5.QtWidgets import QApplication, QPushButton, QVBoxLayout, QWidget, \
QLabel, QVBoxLayout, QMainWindow, QFileDialog
from PyQt5.QtCore import QDir
Next, let’s create a simple PyQt application with a button that triggers the directory selection dialog:
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Directory Selection")
self.setGeometry(100, 100, 300, 200)
layout = QVBoxLayout()
self.select_button = QPushButton("Select Directory")
self.select_button.clicked.connect(self.select_directory)
layout.addWidget(self.select_button)
self.selected_directory_label = QLabel("No directory selected")
layout.addWidget(self.selected_directory_label)
widget = QWidget()
widget.setLayout(layout)
self.setCentralWidget(widget)
def select_directory(self):
# Create a directory dialog and set initial directory to current directory
directory_dialog = QFileDialog(self)
directory_dialog.setFileMode(QFileDialog.Directory)
directory_dialog.setOption(QFileDialog.ShowDirsOnly, True)
if directory_dialog.exec_() == QFileDialog.Accepted:
selected_directory = directory_dialog.selectedFiles()[0]
self.selected_directory_label.setText(selected_directory)
if __name__ == "__main__":
app = QApplication([])
window = MainWindow()
window.show()
app.exec_()
In the MainWindow
class, we create a button that triggers the select_directory
method when clicked. Inside the select_directory
method, we create a QFileDialog
dialog and set it to only show directories. Once a directory is selected by the user, we update the selected_directory_label
with the selected directory.
Testing the Application
Save the code to a file (e.g., main.py
) and run it in your Python environment. You should see a window with a button labeled “Select Directory”. Clicking on the button should open a file dialog where you can navigate through directories and select one. After selecting a directory, the selected directory path should be displayed below the button.
Conclusion
In this blog post, we learned how to use the QDirDialog
class in PyQt to create a directory selection dialog. We created a simple PyQt application that allows users to select a directory and display the selected path. This can be a useful feature in applications that require users to choose a directory for file operations or application settings.