QFileDialog:保存文件时自动添加扩展名?

发布于 2024-08-15 15:41:01 字数 391 浏览 10 评论 0原文

当使用QFileDialog保存文件并指定扩展名(如*.pdf)并且用户输入不带此扩展名的名称时,保存的文件也没有此扩展名。
示例代码:

QFileDialog fileDialog(this, "Choose file to save");
fileDialog.setNameFilter("PDF-Files (*.pdf)");
fileDialog.exec();
QFile pdfFile(fileDialog.selectedFiles().first());

现在,当用户输入“foo”作为名称时,文件将保存为“foo”,而不是“foo.pdf”。因此QFileDialog不会自动添加扩展名。我的问题:我该如何改变这个?

When using a QFileDialog to save a file and to specify the extension (like *.pdf) and the user types in a name without this extension, also the saved file hasn't this extension.
Example-Code:

QFileDialog fileDialog(this, "Choose file to save");
fileDialog.setNameFilter("PDF-Files (*.pdf)");
fileDialog.exec();
QFile pdfFile(fileDialog.selectedFiles().first());

now when the user enters "foo" as the name, the file will be saved as "foo", not as "foo.pdf". So the QFileDialog doesn't add the extension automatically. My question: How can I change this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

屋檐 2024-08-22 15:41:01

您可以使用 QFileDialog::setDefaultSuffix()

如果未指定其他后缀,则将后缀添加到文件名中。

此属性指定添加到文件名(如果尚无后缀)的字符串。后缀通常用于指示文件类型(例如“txt”指示文本文件)。

如果第一个字符是点('.'),则会将其删除。

You could use QFileDialog::setDefaultSuffix():

Suffix added to the filename if no other suffix was specified.

This property specifies a string that is added to the filename if it has no suffix yet. The suffix is typically used to indicate the file type (e.g. "txt" indicates a text file).

If the first character is a dot ('.'), it is removed.

甜`诱少女 2024-08-22 15:41:01

对于多个文件过滤器,可以执行以下操作。

import re
import os

def saveFile(self):
    path, fileFilter = QFileDialog().getSaveFileName(self, "Save file", 
        "", "Gnuplot Files (*.plt)" 
        + ";;" + "Gnuplot Files (*.gp)"
        + ";;" + "Gnuplot Files (*.gpt)"
        + ";;" + "Text Files (*.txt)")

    selectedExt = re.search('\((.+?)\)',fileFilter).group(1).replace('*','')

    # Attach extension as per selected filter, 
    # if file does not have extension.
    if not os.path.splitext(path)[1]:
        path = path + selectedExt

    print(path)

For multiple file filters, the following can be done.

import re
import os

def saveFile(self):
    path, fileFilter = QFileDialog().getSaveFileName(self, "Save file", 
        "", "Gnuplot Files (*.plt)" 
        + ";;" + "Gnuplot Files (*.gp)"
        + ";;" + "Gnuplot Files (*.gpt)"
        + ";;" + "Text Files (*.txt)")

    selectedExt = re.search('\((.+?)\)',fileFilter).group(1).replace('*','')

    # Attach extension as per selected filter, 
    # if file does not have extension.
    if not os.path.splitext(path)[1]:
        path = path + selectedExt

    print(path)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文