PyQt5 - QFileDialog Widget

This widget is a file selector dialog. It enables the user to navigate through the file system and select a file to open or save. The dialog is invoked either through static functions or by calling exec_() function on the dialog object.
Static functions of QFileDialog class (getOpenFileName() and getSaveFileName()) call the native file dialog of the current operating system.
A file filter can also applied to display only files of the specified extensions. The starting directory and default file name can also be set.
Important methods and enumerations of QFileDialog class are listed in the following table −
getOpenFileName()
Returns name of the file selected by the user to open it
getSaveFileName()
Uses the file name selected by the user to save the file
setacceptMode()
Determines whether the file box acts as open or save dialog
QFileDialog.AcceptOpen
QFileDialog.AcceptSave
setFileMode()
Type of selectable files. Enumerated constants are −
QFileDialog.AnyFile
QFileDialog.ExistingFile
QFileDialog.Directory
QFileDialog.ExistingFiles
setFilter()
Displays only those files having mentioned extensions
Both methods of invoking the file dialog are demonstrated in the following example.
The first button invokes the file dialog by the static method.
fname = QFileDialog.getOpenFileName(self, 'Open file', 
   'c:\\',"Image files (*.jpg *.gif)")

The selected image file is displayed on a label widget. The second button invokes the file dialog by calling exec_() method on QFileDialog object.
dlg = QFileDialog()
dlg.setFileMode(QFileDialog.AnyFile)
dlg.setFilter("Text files (*.txt)")
filenames = QStringList()

   if dlg.exec_():
      filenames = dlg.selectedFiles()
The contents of the selected file are displayed in the TextEdit widget.
f = open(filenames[0], 'r')
   with f:
      data = f.read()
      self.contents.setText(data)
The complete code is as follows −
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class filedialogdemo(QWidget):
   def __init__(self, parent = None):
      super(filedialogdemo, self).__init__(parent)
		
      layout = QVBoxLayout()
      self.btn = QPushButton("QFileDialog static method demo")
      self.btn.clicked.connect(self.getfile)
		
      layout.addWidget(self.btn)
      self.le = QLabel("Hello")
		
      layout.addWidget(self.le)
      self.btn1 = QPushButton("QFileDialog object")
      self.btn1.clicked.connect(self.getfiles)
      layout.addWidget(self.btn1)
		
      self.contents = QTextEdit()
      layout.addWidget(self.contents)
      self.setLayout(layout)
      self.setWindowTitle("File Dialog demo")
		
   def getfile(self):
      fname = QFileDialog.getOpenFileName(self, 'Open file', 
         'c:\\',"Image files (*.jpg *.gif)")
      self.le.setPixmap(QPixmap(fname))
		
   def getfiles(self):
      dlg = QFileDialog()
      dlg.setFileMode(QFileDialog.AnyFile)
      dlg.setFilter("Text files (*.txt)")
      filenames = QStringList()
		
      if dlg.exec_():
         filenames = dlg.selectedFiles()
         f = open(filenames[0], 'r')
			
         with f:
            data = f.read()
            self.contents.setText(data)
				
def main():
   app = QApplication(sys.argv)
   ex = filedialogdemo()
   ex.show()
   sys.exit(app.exec_())
	
if __name__ == '__main__':
   main()
The above code produces the following output −
The complete code for exec_() method is as follows −
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class CustomDialog(QFileDialog):

   def __init__(self, *args, **kwargs):
      super(CustomDialog, self).__init__(*args, **kwargs)
      
      self.setWindowTitle("HELLO!")

      QBtn = QDialogButtonBox.Ok | QDialogButtonBox.Cancel

      self.buttonBox = QDialogButtonBox(QBtn)
      self.buttonBox.accepted.connect(self.accept)
      self.buttonBox.rejected.connect(self.reject)

      self.layout = QVBoxLayout()
      self.layout.addWidget(self.buttonBox)
      self.setLayout(self.layout)

class filedialogdemo(QWidget):
   def __init__(self, parent = None):

      super(filedialogdemo, self).__init__(parent)

      layout = QVBoxLayout()

      self.btn1 = QPushButton("QFileDialog object")
      self.btn1.clicked.connect(self.getfiles)
      layout.addWidget(self.btn1)

      self.contents = QTextEdit()
      layout.addWidget(self.contents)
      self.setLayout(layout)
      self.setWindowTitle("File Dialog demo")

   def getfiles(self, s):
      print("click", s)
      dlg = CustomDialog(self)
      if dlg.exec_():
      filenames = dlg.selectedFiles()
      f = open(filenames[0], 'r')

      with f:
         data = f.read()
         self.contents.setText(data)
def main():

   app = QApplication(sys.argv)
   ex = filedialogdemo()
   ex.show()
   sys.exit(app.exec_())

if __name__ == '__main__':
   main()
The above code produces the following output −
Text in selected file will be displayed in TextEdit control.

    146 Lectures 
     22.5 hours 

 ALAA EID
 Print
 Add Notes
 Bookmark this page