How to use QFileDialog options and retrieve saveFileName?

user3161430 picture user3161430 · Jan 5, 2014 · Viewed 45.7k times · Source

I'm trying to use a QFileDialog to prompt a user to provide a filename and location to save a text file at. I played around with the QtGui.QFileDialog.getSaveFileName, but I was interested in using some of the options, like setting the default suffix, and enabling the Detail view of the save file dialog, which, from what I could tell, isn't possible to do, using the getSaveFileName alone. Whenever I set those, the getSaveFileName dialog just ignored them.

So, I ended up with something like this:

dlg=QtGui.QFileDialog( self )
dlg.setWindowTitle( 'Print Things' )
dlg.setViewMode( QtGui.QFileDialog.Detail )
dlg.setNameFilters( [self.tr('Text Files (*.txt)'), self.tr('All Files (*)')] )
dlg.setDefaultSuffix( '.txt' )
if dlg.exec_() :
    print dlg

However, now I'm not sure how to get the name of the file passed by the user? If I print dlg.getSaveFileName, it just pops up another save file dialog. Anybody know how to do this, while still passing all of the options to the QFileDialog that I want to be respected?

Answer

qurban picture qurban · Jan 5, 2014

There is no need to create object of QFileDialog because it provides four static methods which can be used according to your needs.

1) QFileDialog.getExistingDirectory(...)
2) QFileDialog.getOpenFileName(...)
3) QFileDialog.getOpenFileNames(...)
4) QFileDialog.getSaveFileName(...)

according to your needs, you need the 4th one. You can also provide arguments to this function for default file extension. You can use it as:

fileName = QtGui.QFileDialog.getSaveFileName(self, 'Dialog Title', '/path/to/default/directory', selectedFilter='*.txt')
if fileName:
    print fileName

You can leave the /path/to/default/directory as empty string if you don't have any clue that in which directory a user can save the file.

Now when user clicks the save button on the dialog after putting a file name (without file extension), this method will return the file path followed by .txt extension.

More information about QFileDialog.getSaveFileName() can be found here