[英]I can't save .txt file with QFileDialog, C++ QT
This is my code: 这是我的代码:
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();
}
}
}
But it doesn't create any .txt file after click a pushButton: 但是单击按钮后,它不会创建任何.txt文件:
connect(ui->saveButton, SIGNAL(clicked(bool)), this, SLOT(save()));
Log: 日志:
QIODevice::write (QFile, "C:\Users\kfg\Desktop"): device not open
Thanks for your help :) 谢谢你的帮助 :)
You make 2 mistakes. 您犯了两个错误。
The first is here in the line path = info.absoluteDir().absolutePath();
第一个在这里,位于行
path = info.absoluteDir().absolutePath();
This will give you the path of the directory, not the file. 这将为您提供目录路径,而不是文件路径。 You should use
path = info.absoluteFilePath();
您应该使用
path = info.absoluteFilePath();
. 。 See
QFileInfo::absoluteFilePath()
. 参见
QFileInfo::absoluteFilePath()
。
The next is that you write to the "file" when open
returns false
(fails). 其次是当
open
返回false
(失败)时您写入“文件”。
I think for your code to be correct you should use something like this: 我认为为了使您的代码正确,您应该使用以下代码:
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
}
}
}
You might also want to check whether the file already exists and ask the user if it is ok to overwrite it... 您可能还想检查文件是否已经存在,并询问用户是否可以覆盖该文件...
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();
}
}
You should also check whether writing into the file actually succeeded. 您还应该检查写入文件是否实际成功。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.