QFileDialog

QFileDialog is a dialog that allows users to select files or paths.

Users can open the selected files to modify or save them. ( QFileDialog official document )


Example

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QTextEdit, QAction, QFileDialog
from PyQt5.QtGui import QIcon


class MyApp(QMainWindow):

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):

        self.textEdit = QTextEdit()
        self.setCentralWidget(self.textEdit)
        self.statusBar()

        openFile = QAction(QIcon('open.png'), 'Open', self)
        openFile.setShortcut('Ctrl+O')
        openFile.setStatusTip('Open New File')
        openFile.triggered.connect(self.showDialog)

        menubar = self.menuBar()
        menubar.setNativeMenuBar(False)
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(openFile)

        self.setWindowTitle('File Dialog')
        self.setGeometry(300, 300, 300, 200)
        self.show()

    def showDialog(self):

        fname = QFileDialog.getOpenFileName(self, 'Open file', './')

        if fname[0]:
            f = open(fname[0], 'r')

            with f:
                data = f.read()
                self.textEdit.setText(data)


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = MyApp()
    sys.exit(app.exec_())

You have placed the Menu Bar, Text Edit, and Status Bar widgets. The menu contains an ‘Open’ menu for selecting files. Bring the contents of the selected file into the Text Edit widget.


Description

fname = QFileDialog.getOpenFileName(self, 'Open file', './')

Pop up QFileDialog, and use getOpenFileName() method to select the file.

The third parameter allows you to set the default path. Also all files (*) are to be open by default.


if fname[0]:
    f = open(fname[0], 'r')

    with f:
        data = f.read()
        self.textEdit.setText(data)

Read the selected file and bring it to the Edit Text widget via the setText() method.


Results

../_images/5_4_qfiledialog.png ../_images/5_4_qfiledialog_mac.png

Figure 6-4. File Dialog.


Prev/Next