QT4 File Dialog


In this short tutorial you will learn how to create a file dialog and load its file contents. The file dialog is needed in many applications that use file access. To get a filename (not file data) in PyQT you can use the line:

filename = QFileDialog.getOpenFileName(w, 'Open File', '/')

If you are on Microsoft Windows use

filename = QFileDialog.getOpenFileName(w, 'Open File', 'C:\')

An example below (includes loading file data):

#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
from PyQt4.QtGui import *
 
# Create an PyQT4 application object.
a = QApplication(sys.argv) 
 
# The QWidget widget is the base class of all user interface objects in PyQt4.
w = QWidget()
 
# Set window size. 
w.resize(320, 240)
 
# Set window title 
w.setWindowTitle("Hello World!")
 
# Get filename using QFileDialog
filename = QFileDialog.getOpenFileName(w, 'Open File', '/')
print filename
 
# print file contents
with open(filename, 'r') as f:
    print(f.read())
 
# Show window
w.show() 
 
sys.exit(a.exec_())

Result (output may vary depending on your operating system):

pyqt_file_open
PyQt File Open Dialog.

Download PyQT Code (Bulk Collection)


6 thoughts on “QT4 File Dialog

  1. Kevin - June 12, 2016

    How about load an image file and display it?

  2. Melissa - March 26, 2016

    Hi there,
    I’m somewhat at a loss on labels…how do these work in PYQT4
    Thanks
    Melissa

    1. Frank - March 28, 2016

      To add a label to a window you can call QLabel. I made an example:

      import sys
      from PyQt4.QtGui import *
       
      # Create an PyQT4 application object.
      a = QApplication(sys.argv)       
       
      # The QWidget widget is the base class of all user interface objects in PyQt4.
      w = QWidget()
       
      # Add label
      nameLabel = QLabel("A label in PyQT", w)
      nameLabel.move(100, 80)      
       
      # Set window size. 
      w.resize(320, 240)
       
      # Set window title  
      w.setWindowTitle("PyQT Label Example pythonspot.com") 
       
      # Show window
      w.show() 
       
      sys.exit(a.exec_())
  3. Paul b - January 23, 2016

    For windows the line should read:
    filename = QFileDialog.getOpenFileName(w, ‘Open File’, ‘C:\\’)

    You can also just do the following to start in current working directory:
    filename = QFileDialog.getOpenFileName(w, ‘Open File’, ”)

    1. Nanodano - January 29, 2016

      It’s best to choose an option that is cross platform. Another option is to open the file dialog to the users home directory. Here is a cross platform way of doing that with the Python standard library:

      from os.path import expanduser
      home_dir = expanduser(‘~’)

  4. Paul b - January 23, 2016

    Thanks for these great tutorials Frank. They are very helpful!