This is a notes program, you write in the textEdit
and it saves it using fstream
. I am trying to figure out how to load back ALL the words previously typed on the textEdit
, right now only the first word loads back. I think it has something to do with the white spaces.
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <fstream>
using namespace std;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
// Setup code
ui->textEdit->setReadOnly(true);
ui->textEdit->append("Select one of the buttons on the left to pick a log");
}
MainWindow::~MainWindow()
{
delete ui;
}
string buttons;
string lastSavedText[] =
{
" ",
" "
};
QString qLastSavedTextHome, qLastSavedTextWork;
This is the first button
void MainWindow::on_homeButton_clicked()
{
// Preparing text edit
ui->textEdit->setReadOnly(false);
ui->textEdit->clear();
ui->textEdit->setOverwriteMode(true);
buttons = "Home";
// Loading previously saved text
ifstream home;
home.open("home.apl");
home >> lastSavedText[0];
home.close();
qLastSavedTextHome = QString::fromStdString(lastSavedText[0]);
ui->textEdit->setPlainText(qLastSavedTextHome);
}
This next button isn't fully developed yet:
void MainWindow::on_workButton_clicked()
{
// Preparing text edit
ui->textEdit->setReadOnly(false);
ui->textEdit->clear();
buttons = "Work";
// Converts textEdit to string
QString textEditText = ui->textEdit->toPlainText();
string plainText = textEditText.toStdString();
}
This is where I convert the textEdit
to a string and save the textEdit
to a stream:
void MainWindow::on_saveButton_clicked()
{
// Converts textEdit to string
QString textEditText = ui->textEdit->toPlainText();
lastSavedText[0] = textEditText.toStdString();
// Saving files
ofstream home;
home.open("home.apl");
home << lastSavedText[0];
home.close();
}
You are reading only one word in your code:
ifstream home;
home.open("home.apl");
home >> lastSavedText[0]; // Here!!!
home.close();
I'd suggest that you use QFile
for reading and writing to file and it'll be more easier to do.
Here's an example:
QFile file { "home.apl" };
if ( !file.open(QIODevice::ReadOnly | QIODevice::Text) )
{
qDebug() << "Could not open file!";
return;
}
const auto& lastSavedText = file.readAll();
file.close();
ui->textEdit->setPlainText( lastSavedText );
You should use Qt features as much you can. You can directly use QString
instead of std::string
and you won't have to do those conversions.