The file dialog box allows the user to select a file or folder, and the selected file can be read or written.
#!/usr/bin/python#-*-coding:utf-8-*-ImportSYS fromPyQt4ImportQtgui, QtcoreclassOpenFile (Qtgui.qmainwindow):def __init__(Self, parent =None): Qtgui.qwidget.__init__(self, parent) Self.setgeometry (300, 300, 350, 300) Self.setwindowtitle ('Open File') Self.textedit=Qtgui.qtextedit () self.setcentralwidget (Self.textedit) Self.statusbar () Self.setfocus () Exit= Qtgui.qaction (Qtgui.qicon ('Open.png'),'Open', self) exit.setshortcut ('Ctrl+o') Exit.setstatustip ('Open New File') Self.connect (Exit, Qtcore.signal ('triggered ()'), self.showdialog) menubar=self.menubar () file= Menubar.addmenu ('&file') file.addaction (exit)defShowDialog (self): filename= QtGui.QFileDialog.getOpenFileName (self,'Open File','./') file=open (filename) data=File.read () self.textEdit.setText (data) app=qtgui.qapplication (SYS.ARGV) of=OpenFile () of.show () Sys.exit (App.exec_ ())
Effect:
In this example program, we show a menu bar, a status bar, and a text editor that is set as a central part. Status information in the status bar is displayed only if the user wants to open the file. Clicking the Open option in the menu bar pops up the file dialog box for the user to select the file. The selected file content will be displayed in the text editor part.
Class OpenFile (Qtgui.qmainwindow):
......
Self.textedit = Qtgui.qtextedit ()
Self.setcentralwidget (Self.textedit)
This sample program is based on the Qmainwindow widget because we need to set the text editor as the central part (the Qwidget class does not provide the Setcentralwidget method). Without relying on the layout manager, Qmainwindow can easily perform the work of the Configuration center part (using the Setcentralwidget method).
filename = QtGui.QFileDialog.getOpenFileName (self, ' Open file ', './')
The statement pops up a file dialog box. The first string parameter of the GetOpenFileName () method ' Open File ' is displayed in the title bar of the popup dialog box. The second string parameter is used to specify the working directory of the dialog box. By default, the file filter is set to not filter any files (all files/folders in the working directory will be displayed).
FILE = open (filename)
data = File.read ()
Self.textEdit.setText (data)
The above three lines of statements will read the selected file and display its contents in the text compiler.
PyQt4 file dialog Box Qfiledialog