How to save documents when X-Button is pressed
-
Hello,
my program should show a MessageBox with the question to save the progress. I tried to override the function closeEvent in my subclass from QWidget, but my programm closes without showing the QMessageBox. -
Hi,
Can you show your widget implementation ?
-
This post is deleted!
-
What is AddAvailableFoodView ?
Note that pasting the code here between coding tags allows for easier reading and copy pasting to test which an image does not.
-
It is very easy!
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include "QCloseEvent" #include "QMessageBox" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); protected: void closeEvent(QCloseEvent *event) override; private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow(){ delete ui; } void MainWindow::closeEvent(QCloseEvent *event) { switch (QMessageBox(tr("Warning!"), tr("Are you sure you want to exit without save?"), QMessageBox::Warning, QMessageBox::Yes | QMessageBox::Default, QMessageBox::No, QMessageBox::Escape).exec()) { case 3: { event->accept(); break; } default: { event->ignore(); break; } } }
-
void AddAvailableFoodView::closeEvent(QCloseEvent event)
{
QMessageBox saveOrNot = new QMessageBox();
QPushButton* save = new QPushButton();
saveOrNot->addButton(save);}
I want that my programm saves my progress, if I push the "save" button
-
class AddAvailableFoodView : public QWidget
{
Q_OBJECT
public:
explicit AddAvailableFoodView(ErrorModel* errorModel, QStackedWidget* stackedWidget, QStringList* widgets,
SearchModel* searchmodel, ManageModel* manageModel,
StackHistoryView* stackHistoryView, QWidget* parent = nullptr);
void createStartLayout(void);protected:
virtual void closeEvent(QCloseEvent *event) override; -
closeEvent comes from Widget.
Take a look at the Main Window Example it shows what you want to achieve.
-
@Michelle02283
use saving method in close event ,before accept event...
like this:void MainWindow::closeEvent(QCloseEvent *event) { QMessageBox::StandardButton res=QMessageBox::question(this, "title","exit?", QMessageBox::Yes|QMessageBox::No); if(res==QMessageBox::Yes) { qDebug()<<"exit: Yes"; SaveFunc();//saveig method event->accept();//exit } else { event->ignore(); } } void MainWindow::SaveFunc() { qDebug()<<"saving"; Sleep(3000); qDebug()<<"ok saved"; }
program after 3 second closing...