Monday, October 6, 2008

File Dialogs in PyQt4

The following code is an example of how to setup a simple open file dialog prompt. Two versions are shown using the following code, the open file dialog and the open directory dialog. More examples may be found in the PyQt4 source code examples and also from the great general tutorial found at zetcode.


#!/usr/bin/python

from PyQt4 import QtCore, QtGui
import os

class OFD_Class(QtGui.QWidget):
def __init__(self, parent = None):
QtGui.QWidget.__init__(self, parent)
self.curDir = os.getcwd()

def PyQt4_OFD(self):
directory= QtGui.QFileDialog.getExistingDirectory(self, "Select Folder", self.curDir)
if directory:
#if user selected a directory...do something
print directory
#remember that PyQt returns QStrings which are unicode object and need to be handled appropriately
print type(directory)

dataFileName = QtGui.QFileDialog.getOpenFileName(self,\
"Select File",\
self.curDir, 'X!Tandem XML (*.xml);; HDF5 File (*.h5);;SQLite Database (*.db);;All Files (*.*)')
if dataFileName:
#if file selected...do something
print dataFileName
print type(dataFileName)

def main():

import sys
app = QtGui.QApplication(sys.argv)

OFD = OFD_Class()
OFD.PyQt4_OFD()

sys.exit(app.exec_())



if __name__ == "__main__":
main()

No comments: