How to use QFileDialog options and retrieve saveFileName?

喜你入骨 提交于 2019-12-31 22:37:28

问题


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?


回答1:


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




回答2:


dlg.selectedFiles() returns a list of unicode strings containing the filenames selected.



来源:https://stackoverflow.com/questions/20928023/how-to-use-qfiledialog-options-and-retrieve-savefilename

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!