简体   繁体   English

如何使用QFileDialog选项并检索saveFileName?

[英]How to use QFileDialog options and retrieve saveFileName?

I'm trying to use a QFileDialog to prompt a user to provide a filename and location to save a text file at. 我正在尝试使用QFileDialog来提示用户提供文件名和位置以保存文本文件。 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. 我玩了QtGui.QFileDialog.getSaveFileName,但我有兴趣使用一些选项,比如设置默认后缀,并启用保存文件对话框的详细信息视图,据我所知,这不是可以这样做,仅使用getSaveFileName。 Whenever I set those, the getSaveFileName dialog just ignored them. 每当我设置它们时,getSaveFileName对话框就会忽略它们。

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. 如果我打印dlg.getSaveFileName,它只会弹出另一个保存文件对话框。 Anybody know how to do this, while still passing all of the options to the QFileDialog that I want to be respected? 任何人都知道如何做到这一点,同时仍然将所有选项传递给我想要尊重的QFileDialog?

There is no need to create object of QFileDialog because it provides four static methods which can be used according to your needs. 不需要创建QFileDialog对象,因为它提供了四种静态方法,可以根据您的需要使用。

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. 如果您没有任何线索知道用户可以在哪个目录中保存文件,则可以将/path/to/default/directory保留为空字符串。

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. 现在,当用户在放置文件名(没有文件扩展名)后单击对话框上的保存按钮时,此方法将返回文件路径,后跟.txt扩展名。

More information about QFileDialog.getSaveFileName() can be found here 有关QFileDialog.getSaveFileName()更多信息,请访问此处

dlg.selectedFiles()返回包含所选文件名的unicode字符串列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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