connorb08 connorb08 - 3 months ago 45
C++ Question

QT With C++: How to implement Save As

I'm trying to add a save as feature to a simple text editor I'm making with C++ and QT. I'm attempting to close the current tab when you save your file and open a new tab with the same index and has the name of the new file as the tab title. This is my code:

QString fileName = QFileDialog::getSaveFileName(this, tr("Save As"), "", tr("All Files (*)"));
if (fileName.isEmpty())
return;
else
{
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly))
{
QMessageBox::information(this, tr("Unable to open file"),
file.errorString());
return;
}
QTextStream out (&file);`

out << ui->plainTextEdit->toPlainText();


QFileInfo FileData(file);

int currentTab = ui->tabWidget->currentIndex();
ui->tabWidget->removeTab(currentTab);
QTextStream InputData(&file);
ui->tabWidget->insertTab(currentTab, new Form(), FileData.fileName());
ui->tabWidget->setCurrentIndex(currentTab);
ui->plainTextEdit->setPlainText(InputData.readAll());

file.flush();
file.close();
}


When I try to save the new file, it saves the file to the selected location and replaces the current tab with the file name, but it doesn't write the file to the text window. Any help would be great.

Answer

Here is my demo code and it seems to work:

form.cpp which has a plainTextEdit

#include "form.h"
#include "ui_form.h"

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

Form::~Form()
{
    delete ui;
}

QString Form::GetText()
{
    return ui->plainTextEdit->toPlainText();
}

void Form::SetText(QString text)
{
    ui->plainTextEdit->setPlainText(text);
}

And the mainwindow.cpp which contains a QTabWidget

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "form.h"

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

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

void MainWindow::on_pushButton_clicked()
{
    ui->tabWidget->insertTab(0, new Form(), "My File");
    ui->tabWidget->setCurrentIndex(0);
}

void MainWindow::on_pushButton_2_clicked()
{
    int currentIndex = ui->tabWidget->currentIndex();

    //Save the text to a file or a variable...
    QString content = static_cast<Form*>(ui->tabWidget->widget(currentIndex))->GetText();

    ui->tabWidget->removeTab(currentIndex);

    ui->tabWidget->insertTab(currentIndex, new Form(), "Saved File");//new name
    static_cast<Form*>(ui->tabWidget->widget(currentIndex))->SetText(content);
    ui->tabWidget->setCurrentIndex(currentIndex);
}

It is working for me, please try. Thank You.