From 35e33581cc103592183a20f9adfd216acbf553ac Mon Sep 17 00:00:00 2001 From: Michael Mandl Date: Sun, 30 Sep 2018 11:38:30 +0200 Subject: [PATCH] Fix #11: Ask to save modfications when opening a new file --- source/mainwindow.cpp | 57 ++++++++++++++++++------------------------- source/mainwindow.h | 1 + 2 files changed, 25 insertions(+), 33 deletions(-) diff --git a/source/mainwindow.cpp b/source/mainwindow.cpp index 9b07977..eb1ba77 100644 --- a/source/mainwindow.cpp +++ b/source/mainwindow.cpp @@ -35,6 +35,8 @@ MainWindow::~MainWindow() void MainWindow::newFile() { + closeFile(); + m_dataModel = std::make_unique(this); ui->metaDataWidget->setModel(&m_dataModel->m_metaData); ui->verbEndWidget->setModel(&m_dataModel->m_verbEnd); @@ -66,6 +68,8 @@ void MainWindow::openFile() return; } + closeFile(); + QFile loadFile(filename); if (!loadFile.open(QFile::ReadOnly)) { @@ -110,47 +114,32 @@ void MainWindow::saveFileAs() saveFile(filename); } +void MainWindow::closeFile() +{ + if (m_saveOnClose == true) + { + QMessageBox msgBox; + msgBox.setText("The document has been modified."); + msgBox.setInformativeText("Do you want to save your changes?"); + msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard); + msgBox.setDefaultButton(QMessageBox::Save); + + if (msgBox.exec() == QMessageBox::Save) + { + saveFile(); + } + } +} + void MainWindow::dataModelChanged() { - qDebug() << "data model changed"; - m_saveOnClose = true; setWindowModified(true); } void MainWindow::closeEvent(QCloseEvent *event) { - if (m_saveOnClose == false) - { - event->accept(); - return; - } - - QMessageBox msgBox; - msgBox.setText("The document has been modified."); - msgBox.setInformativeText("Do you want to save your changes?"); - msgBox.setStandardButtons( - QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); - msgBox.setDefaultButton(QMessageBox::Save); - int ret = msgBox.exec(); - - switch (ret) - { - case QMessageBox::Save: - saveFile(); - if (m_saveOnClose == true) - { - event->ignore(); - break; - } - case QMessageBox::Discard: - event->accept(); - break; - case QMessageBox::Cancel: - default: - event->ignore(); - break; - } + closeFile(); } void MainWindow::saveFile(const QString &filename) @@ -165,6 +154,8 @@ void MainWindow::saveFile(const QString &filename) saveFile.write(saveDoc.toJson()); saveFile.close(); + qDebug() << "Wrote" << filename; + setWindowTitle(filename + "[*]"); setWindowModified(false); m_filename = filename; diff --git a/source/mainwindow.h b/source/mainwindow.h index 5c6d31f..ab9424f 100644 --- a/source/mainwindow.h +++ b/source/mainwindow.h @@ -30,6 +30,7 @@ public slots: void openFile(); void saveFile(); void saveFileAs(); + void closeFile(); void dataModelChanged(); protected: