[英]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.