Qt创建文件夹 QDir类

时间:2024-03-27 17:55:32

首先创建一个lineEdit和pushButton成员变量和一个createFolderSlot()槽函数

private:
    QLineEdit *lineEdit;
    QPushButton *pushButton;
private slots:
    void createFolderSlot();

构造函数中:

    lineEdit = new QLineEdit(this);
    lineEdit->setGeometry(QRect(50, 50, 200, 25));
    pushButton = new QPushButton(this);
    pushButton->setGeometry(QRect(280, 50, 80, 25));
    pushButton->setText("Create");
    connect(pushButton, &QPushButton::clicked, this, &MainWindow::createFolderSlot);

槽函数实现:

void MainWindow::createFolderSlot()
{
    QDir *folder = new QDir;
    bool exist = folder->exists(lineEdit->text());
    if(exist)
    {
        QMessageBox::warning(this, tr("createDir"), tr("Dir is already existed!"));
    }
    else
    {
        //创建文件夹
        bool ok = folder->mkdir(lineEdit->text());
        if(ok)
            QMessageBox::warning(this, tr("CreateDir"), tr("Create Dir success!"));
        else
            QMessageBox::warning(this, tr("CreateDir"), tr("Create Dir fail"));
    }
}

如下图,输入要创建的文件夹的路径,点击Create创建

Qt创建文件夹 QDir类