简体   繁体   中英

How to know the file's type to save, using QFileDialog

About pyQt4

I prefer to use the static method for the getSaveFilename in the QFileDialog so that the user sees the Windows/Mac native dialog.

My problem is that if the user doesn't type the file extension the in the save file name (say when selecting an image type to save a file as), then I don't have a way of checking to see what type of file they wanted to save as.

How can I create a dialog to save files with a filter, and how to know which filter the user chose?

For example:

files_types = "GML (*.gml);;Pickle (*.pickle);;YAML (*.yml)"
file = QtGui.QFileDialog.getSaveFileName(self, 'Save file', '', files_types)

With var file I'll have only the file's path, but I'm not sure whats the format that user chose.

So, I wanna know how could I get the extension, or the files type chosen by user. Is there away to get the selectedFilter using this method?

Thanks a lot!

You can use the getSaveFileNameAndFilter() method:

filename, filter = QtGui.QFileDialog.getSaveFileNameAndFilter(self, 'Save file', '', files_types)

(In PySide however, getSaveFileNameAndFilter() does not exist, and getSaveFileName() already behaves that way. I'm not sure whether this is also the case for PyQT api version 2, which is the default for Python 3)

In PyQt5 just use:

files_types = "GML (*.gml);;Pickle (*.pickle);;YAML (*.yml)"
options = QFileDialog.Options()
filename, _ = QFileDialog.getSaveFileName(
            self, 'Save as... File', 'untitled.gml', filter=file_types,options=options)

Its not possible.

The only way to do this, is creating a generical dialog, but by another hand you will lost the pretty native windows.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM