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:
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();
This will give you the path of the directory, not the file. You should usepath = info.absoluteFilePath();
. SeeQFileInfo::absoluteFilePath()
.The next is that you write to the "file" when
open
returnsfalse
(fails).I think for your code to be correct you should use something like this:
You might also want to check whether the file already exists and ask the user if it is ok to overwrite it...
You should also check whether writing into the file actually succeeded.