How to create a file dialog in PyQt5?

In PyQt5, you can use the QFileDialog class to create a file dialog. Here is a simple example code demonstrating how to create a file dialog:

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QFileDialog

class FileDialogExample(QMainWindow):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        self.setWindowTitle('File Dialog Example')
        self.setGeometry(100, 100, 400, 300)

        button = QPushButton('Open File Dialog', self)
        button.clicked.connect(self.showFileDialog)
        button.move(150, 100)

    def showFileDialog(self):
        options = QFileDialog.Options()
        fileName, _ = QFileDialog.getOpenFileName(self, 'Open File', '', 'All Files (*);;Text Files (*.txt)', options=options)
        
        if fileName:
            print('Selected file:', fileName)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = FileDialogExample()
    ex.show()
    sys.exit(app.exec_())

Running this code will create a window and a button. When the button is clicked, a file dialog will pop up, allowing the user to select a file. After the selection is made, the selected file path will be printed on the console.

 

More tutorials

How to add a menu bar in PyQt5?(Opens in a new browser tab)

What is the purpose of the QThread class in PyQt5?(Opens in a new browser tab)

Using Classes in Tkinter Advanced Techniques(Opens in a new browser tab)

How do you add environment variables in Java?(Opens in a new browser tab)

Toggle button in Android(Opens in a new browser tab)

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds