-1

So I am writing the code for a notepad clone which I hope would evolve into a final draft clone in further updates, and I am using it as a tool to learn C++ and QT as I am still Quite a beginner with the langauge.

I have implemented a save function into the application, which when pressed should take the text written in the Textedit widget and write it into a file, but what seems to happen is that when I call that function it creates said file but leaves it empty without adding the text into it

this is my code


void MainWindow::on_actionSave_as_triggered()
{
    QString File_name = QFileDialog::getSaveFileName(this, "Save File as");
    QFile File(File_name);
    if(!File.open(QIODevice::WriteOnly) | QFile::Text) {
        QMessageBox::warning(this, "Save warning", "Error: File Did not save properly" + File.errorString());
        return;
    }
    current_file = File_name;
    setWindowTitle(File_name);
    QTextStream out(&File);
    QString writing = ui->textEdit->toPlainText();
    out << writing;
    File.flush();
    File.close();
}

here is the entire cpp file:

#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include <iostream>
#include <stream>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
,     ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete UI;
}


void MainWindow::on_actionNew_triggered()
{
    current_file.clear();
    ui->textEdit->setText(QString());
}


void MainWindow::on_actionSave_triggered()
{


}


void MainWindow::on_actionOpen_triggered()
{
QString File_name = QFileDialog::getOpenFileName(this, "Open the 
File");
 QFile File(File_name);
 current_file = File_name;
 if(!File.open(QIODevice::ReadOnly | QFile::Text)){
     QMessageBox::warning(this,"warning", "Error, File Could not 
open");
     return;
 }
 setWindowTitle(File_name);
 QTextStream in(&File);
 QString Writing = in.readAll();
 ui->textEdit->setText(Writing);
 File.close();
}


void MainWindow::on_actionSave_as_triggered()
{
    QString File_name = QFileDialog::getSaveFileName(this, "Save File as");
    QFile File(File_name);
    if(File.open(QFile::WriteOnly | QFile::Text)) {
        QMessageBox::warning(this, "Save warning", "Error: File Did not save properly" + File.errorString());
        return;
    }
    current_file = File_name;
    setWindowTitle(File_name);
    QTextStream out(&File);
    QString writing = ui->textEdit->toPlainText();
    out << writing;
    File.flush();
    File.close();
}

edit: Tried removing, File.flush and .close but I still get the unknown error

Zayn Mady
  • 9
  • 2

1 Answers1

0

I think you need

out.flush();

instead of

File.flush();

(or just drop it altogether).

And you don't need File.close(), it is automatic for files.

The way you've coded it, the file gets closed before the QTextStream writes data to it.

jpalecek
  • 47,058
  • 7
  • 102
  • 144