[英]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
謝謝你的幫助 :)
您犯了兩個錯誤。
第一個在這里,位於行path = info.absoluteDir().absolutePath();
這將為您提供目錄路徑,而不是文件路徑。 您應該使用path = info.absoluteFilePath();
。 參見QFileInfo::absoluteFilePath()
。
其次是當open
返回false
(失敗)時您寫入“文件”。
我認為為了使您的代碼正確,您應該使用以下代碼:
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();
}
}
您還應該檢查寫入文件是否實際成功。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.