Функция Qdir существует () всегда возвращает true, даже если каталог не существует - PullRequest
2 голосов
/ 09 июня 2011

Я пытаюсь защитить от ошибок первую часть проекта, в которой папка создается в указанной базовой директории.Базовый каталог выбирается пользователем либо вручную в QLineEdit, либо путем просмотра каталогов компьютера с помощью QFileDialog.Я пытаюсь проверить, существует ли базовый каталог, прежде чем я создаю в нем подпапку, используя следующие команды:

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;
    }
}

Проблема заключается в том, введите ли я правильный каталог в строку edit илинедопустимая (т. е. случайная фраза) вторая, если оператор всегда возвращает false, то есть существует () всегда возвращает true.Первый оператор if работает правильно.Я просто использую существующие () неправильно?

Редактировать: Полный код

#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

}

1 Ответ

2 голосов
/ 09 июня 2011

Ваш второй оператор if не будет выполнен, если вы введете что-либо в текстовое поле.Ваша логика в первом случае гласит, что если ввод пустой или предопределенной строки, то проверяется наличие dir.Это означает, что вы всегда тестируете с пустой строкой или стандартным сообщением.

Правильная логика должна быть:

if( base_dir!=no_text1 && base_dir!=blank ) {
    ....
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...