我无法使用 QFileDialog、C++ QT 保存 .txt 文件

I can't save .txt file with QFileDialog, C++ QT

这是我的代码:

void MainWindow::save(){
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save Text File"), path, tr("Text Files (*.txt)"));
    if (fileName != "")
    {
       QFileInfo info(fileName);
       path = info.absoluteDir().absolutePath();
       QFile file(path);
       if(!file.open(QIODevice::WriteOnly)){
           QString text = ui->plainTextEdit->toPlainText();
           QTextStream out(&file);
           out << text ;
           file.close();
       }
    }
}

但它在单击按钮后不会创建任何 .txt 文件:

connect(ui->saveButton, SIGNAL(clicked(bool)), this, SLOT(save()));

日志:

QIODevice::write (QFile, "C:\Users\kfg\Desktop"): device not open

感谢您的帮助:)

你犯了 2 个错误。

第一个在path = info.absoluteDir().absolutePath();行中 这将为您提供目录的路径,而不是文件的路径。你应该使用 path = info.absoluteFilePath();。参见 QFileInfo::absoluteFilePath()

接下来是当open returns false(失败)时写入"file"。

我认为你的代码是正确的,你应该使用这样的东西:

void MainWindow::save() 
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save Text File"), path, tr("Text Files (*.txt)"));
    if (fileName != "")
    {
        QFile file(QFileInfo(fileName).absoluteFilePath());
        if (file.open(QIODevice::WriteOnly))
        {
            QString text = ui->plainTextEdit->toPlainText();
            QTextStream out(&file);
            out << text;
            file.close();
        }
        else
        {
            //TODO: Error message
        }
    }
}

您可能还想检查文件是否已经存在并询问用户是否可以覆盖它...

void MainWindow::save() 
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save Text File"), path, tr("Text Files (*.txt)"));
    if (fileName != "")
    {
        QFile file(QFileInfo(fileName).absoluteFilePath());

        if (file.exists())
        {
            QMessageBox::StandardButton chosenButton 
                = QMessageBox::warning(this, tr("File exists"), tr("The file already exists. Do you want to overwrite it?"), 
                    QMessageBox::Ok | QMessageBox::Cancel, 
                    QMessageBox::Cancel);
            if (chosenButton != QMessageBox::Ok)
            {
                return; //Save was cancelled
            }
        }
        if (!file.open(QIODevice::WriteOnly))
        {
            QMessageBox::critical(this, tr("Error"), tr("Failed to save file"));
            return; //Aborted
        }
        //All ok - save data
        QString text = ui->plainTextEdit->toPlainText();
        QTextStream out(&file);
        out << text;
        file.close();
    }
}

您还应该检查写入文件是否真的成功了。