我试图在指定的基本目录中创建一个文件夹的项目的第一部分进行防错。基本目录由用户在QLineEdit中手动选择,或者使用QFileDialog浏览计算机的目录。我想,如果存在的基本目录之前,我使用下面的命令使一个子文件夹中它来检查:Qdir的函数exists()始终返回true,即使该目录不存在
QString base_dir = ui->baseDir->text();
QString blank = "";
QString no_text1 = "Please enter a valid directory";
if(base_dir==no_text1 || base_dir==blank) {
if(!QDir(base_dir).exists()) { //does base directory exist?
ui->baseDir->setText(no_text1);
return;
}
}
的问题是,我是否键入一个有效的目录进行编辑,或无效一个(即随机短语)第二个if语句总是返回false,意味着exists()总是返回true。第一条if语句正常工作。我只是使用exists()错误?
编辑: 完整的代码
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "functions.h"
#include <QtGui/QApplication>
#include <QFileDialog>
#include <fstream>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
// This is the function that handles the directory search when the 'browse' button is pressed
void MainWindow::on_findDir_clicked()
{
QString path; //declaring the path to the base directory
path = QFileDialog::getExistingDirectory( //gathering the directory from QFileDialog class
this, tr("Choose the project directory"),
"/home",
QFileDialog::ShowDirsOnly
| QFileDialog::DontResolveSymlinks);
ui->baseDir->setText(path); //setting the retrieved path into the line edit box
}
// This function makes the project by creating a new directory with name 'project_name'
// in the base directory, and collects the OpenFOAM version number and simulation type
void MainWindow::on_create_clicked()
{
QString project_name, foam_version, full_dir, slash, base_dir;
base_dir = ui->baseDir->text();
project_name = ui->projectName->text(); //getting the text from the 'projectName' field
foam_version = ui->version->currentText(); //getting the selection from the 'version' drop-down box
//first checking if the fields have input in them:
QString blank = "";
QString no_text0 = "Please enter project name";
if(project_name==no_text0 || (project_name==blank)) {
ui->projectName->setText(no_text0);
return;
}
QString no_text1 = "Please enter a valid directory";
if(base_dir==no_text1 || base_dir==blank) {
if(!QDir(base_dir).exists()) { //does base directory exist?
ui->baseDir->setText(no_text1);
return;
}
}
slash = "/"; // needed to separate folders in the directory (can't use a literal)
full_dir = base_dir.append(slash.append(project_name));
if(!QDir(full_dir).exists()) //check if directory already exists
QDir().mkdir(full_dir); //creating directory
QString blockmesh_filename, suffix;
suffix = "_blockmesh";
slash = "/"; //must re-define
blockmesh_filename = full_dir.append(slash.append(project_name.append(suffix)));
std::ofstream create_file(blockmesh_filename.toStdString().c_str()); //creating empty blockmesh file
}
'的QDir(base_dir).exists()'? '〜'是按位补充的。 – Vlad 2011-06-09 17:23:26
哎呀抱歉有多尴尬,当我把它放在这里时,我错误地输入了代码。固定。虽然这个错误并不在我的实际代码中,但错误仍在发生。 – 2011-06-09 17:31:19
您是否输入绝对路径或相对路径到变量'base_dir' – Abhijith 2011-06-09 17:36:14