qt QFileDialog 保存文件 没有扩展名
way1. 根据 selectedNameFilter 接受类型选择
您希望在选择不同文件类型时自动添加扩展名,您可以在用户选择文件后检查文件的扩展名并自动添加相应的扩展名。以下是一个示例,演示如何在用户选择文件后自动添加扩展名:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | QFileDialog dialog( this ); dialog.setFileMode(QFileDialog::AnyFile); dialog.setNameFilter( "文本文件 (*.txt);;位图文件 (*.bmp);;所有文件 (*)" ); if (dialog.exec()) { QStringList selectedFiles = dialog.selectedFiles(); QString selectedFilePath = selectedFiles.first(); // 获取用户选择的文件过滤器 QString selectedFilter = dialog.selectedNameFilter(); // 根据选择的过滤器设置默认扩展名 if (selectedFilter == "文本文件 (*.txt)" ) { if (!selectedFilePath.endsWith( ".txt" , Qt::CaseInsensitive)) { selectedFilePath += ".txt" ; } } else if (selectedFilter == "位图文件 (*.bmp)" ) { if (!selectedFilePath.endsWith( ".bmp" , Qt::CaseInsensitive)) { selectedFilePath += ".bmp" ; } } // 在这里使用selectedFilePath来保存文件 } |
way2. fileDialog.setDefaultSuffix(".bmp");
way3.在用户选择文件过程中改变文件扩展名
用户选择文件过程中实时改变文件扩展名需要创建一个自定义的文件对话框,并在用户选择文件过程中监视所选文件类型以动态设置扩展名。这可以通过使用QFileDialog
的子类化来实现。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | #include <QFileDialog> #include <QFileInfo> class CustomFileDialog : public QFileDialog { Q_OBJECT public : CustomFileDialog(QWidget* parent = nullptr ) : QFileDialog(parent) { //setOption(QFileDialog::DontUseNativeDialog, true); // 使用Qt的文件对话框而不是操作系统的原生对话框 setNameFilter( "文本文件 (*.txt);;位图文件 (*.bmp);;所有文件 (*)" ); setAcceptMode(QFileDialog::AcceptSave); // 设置对话框为保存模式 } QString selectedFilePath() const { QString selectedFile = selectedFiles().isEmpty() ? QString() : selectedFiles().first(); if (!selectedFile.isEmpty()) { // 获取用户选择的文件过滤器 QString selectedFilter = selectedNameFilter(); // 根据选择的过滤器设置默认扩展名 if (selectedFilter == "文本文件 (*.txt)" ) { if (!selectedFile.endsWith( ".txt" , Qt::CaseInsensitive)) { selectedFile += ".txt" ; } } else if (selectedFilter == "位图文件 (*.bmp)" ) { if (!selectedFile.endsWith( ".bmp" , Qt::CaseInsensitive)) { selectedFile += ".bmp" ; } } } return selectedFile; } }; int main( int argc, char *argv[]) { QApplication app(argc, argv); CustomFileDialog dialog; if (dialog.exec()) { QString selectedFilePath = dialog.selectedFilePath(); if (!selectedFilePath.isEmpty()) { // 在这里使用selectedFilePath来保存文件 } } return app.exec(); } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 字符编码:从基础到乱码解决