如何判断 QFileDialog 是否已关闭而不选择文件
How can I tell if a QFileDialog was closed without selecting a file?
几天我一直在试图弄清楚这一点,但还没有弄清楚。基本上我正在使用QFileDialog来选择一个文件,但是如果我关闭窗口而不选择一个文件,程序就会崩溃。如何判断是否未选择文件?这是我正在使用的代码:
QFileDialog loadFile(this);
loadFile.setFileMode(QFileDialog::AnyFile);
QString filename = "";
loadFile.exec();
这是我用来获取所选文件的代码。
selectedFiles = loadFile.selectedFiles();
filename = selectedFiles.at(0);
我试过使用 {if (dialog.selectedFiles.at(0( != " }以查看是否没有选定的文件,但它不起作用。如果我选择一个文件,它将很好地运行 if 语句中的代码。
非常感谢或任何帮助!
如果在未选择文件的情况下关闭对话框,则列表selectedFiles
为空,如果您尝试访问元素,则会出现崩溃(该函数对于无效索引不安全(。
你想要的是检查用户是否选择了任何东西。
QString filename;
QFileDialog loadFile(this);
loadFile.setFileMode(QFileDialog::AnyFile);
loadFile.exec(); // You could check the return value here to see if the user canceled or not
QStringList selectedFiles = loadFile.selectedFiles();
if (!selectedFiles.isEmpty())
{
filename = selectedFiles.at(0);
// Do something with the filePath...
}
你需要
做的是检查exec((的返回值,如下所示...
if( !loadFile.exec() )
{
// The user pressed the cancel button so handle this accordingly
}
else
{
// At least one file was selected because the user cannot click the 'open' button unless a file selection has been made so continue as normal
}
相关文章:
- 如何选择在 csv 文件中输出的位置
- 防止在C++中选择错误文件时提升 xml 解析器崩溃
- 选择文件对话框错误
- 限制用户可以在 QFileDialog 中选择的文件数量
- 如何从目录迭代器中选择特定文件并进行比较
- 如果在VC6中使用打开功能,如何选择文件夹?
- 选择特定版本的 Visual Studio 命令行工具包,并根据特定版本的C++运行时环境编译文件
- 在 Win32 应用中,如果未选择文件夹并且用户单击"确定",则文件夹选择对话框将关闭
- 如何从文件夹树中快速选择随机文件?
- 使用柯南和cmake选择文件
- C++ gtkmm:文件选择器对话框不适用于任何驱动器
- 使用文件对话框选择包含特定文件类型的文件夹?
- 如何选择文件保存到的位置?
- 如何为多个文件处理选择最佳的I/O策略
- 在为 Java 编译动态链接文件时,我应该选择哪些 g++ 参数
- C++文件选择窗口
- 仅为QFileSystemModel的第一列(驱动器、文件夹、文件)选择选项
- Qt中的文件选择
- CFileDialog多文件选择的问题
- 处理多个文件选择