Solved close button to call a function
-
Hi,
How do I enable the
close
button on the widget to do call some functions? -
Hi
Do you mean the close button on a Window?
If yes, you can override closeEvent and ask user stuff or what you need.
Do note you must call event->accept(); to let it close or event->ignore(); to stay open.#include <QCloseEvent> void MainWindow::closeEvent (QCloseEvent *event) { QMessageBox::StandardButton resBtn = QMessageBox::question( this, APP_NAME, tr("Are you sure?\n"), QMessageBox::Cancel | QMessageBox::No | QMessageBox::Yes, QMessageBox::Yes); if (resBtn != QMessageBox::Yes) { event->ignore(); } else { event->accept(); } }
-
@mrjj Thanks a lot! that's exactly what I meant :)
-
@mrjj I see strange behaviour,:
I seeclose
button dialogue even if I press other buttons on the screen. What might be the issue?I do as follows:
private: void closeEvent (QCloseEvent *event); #include <QCloseEvent> void MainWindow::closeEvent (QCloseEvent *event) { QMessageBox::StandardButton resBtn = QMessageBox::question( this, "My App", tr("Are you sure what to close the application?\n"), QMessageBox::Cancel | QMessageBox::No | QMessageBox::Yes, QMessageBox::Yes); if (resBtn != QMessageBox::Yes) { event->ignore(); } else { event->accept(); } }
-
Hi
It will show when ever the MainWindow will be closed no matter if with X or calling close();- even if I press other buttons on the screen.
And what does these buttons do ?
-
@mrjj Ah I see. Another button closes the current window and opens a new window.
How do we make the dialogue appear only when the user press the
close
button? -
@russjohn834
add a bool AskUser to your class and simply allow to close setting it to false for the
cases where you don't want to ask and true where you do.closeEvent will be called by Qt regardless of X or close() so you have to add some logic by hand to avoid some cases.
-
@mrjj Thanks for your suggestions :)