如何判断 QFileDialog 是否已关闭而不选择文件

How can I tell if a QFileDialog was closed without selecting a file?

本文关键字:文件 选择 是否 何判断 判断 QFileDialog      更新时间:2023-10-16

几天我一直在试图弄清楚这一点,但还没有弄清楚。基本上我正在使用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
}