QCloseEvent sent when you call QWidget::close() to close a widget programmatically... So you just have to reimplement MainWindow::closeEvent(QCloseEvent *event) if you want to control this event. This event fires when you click x or call close() from the code.
Qt employs the signals and slots paradigm. You don't check if a button is clicked. When a button is clicked, it emits a signal. You can connect your own functions to that signal.
Detailed Description. Close events are sent to widgets that the user wants to close, usually by choosing "Close" from the window menu, or by clicking the X title bar button. They are also sent when you call QWidget::close() to close a widget programmatically.
[static] int QApplication::exec()Enters the main event loop and waits until exit() is called, then returns the value that was set to exit() (which is 0 if exit() is called via quit()). It is necessary to call this function to start event handling.
If you have a QMainWindow
you can override closeEvent
method.
#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();
}
}
If you're subclassing a QDialog
, the closeEvent
will not be called and so you have to override reject()
:
void MyDialog::reject()
{
QMessageBox::StandardButton resBtn = QMessageBox::Yes;
if (changes) {
resBtn = QMessageBox::question( this, APP_NAME,
tr("Are you sure?\n"),
QMessageBox::Cancel | QMessageBox::No | QMessageBox::Yes,
QMessageBox::Yes);
}
if (resBtn == QMessageBox::Yes) {
QDialog::reject();
}
}
Well, I got it. One way is to override the QWidget::closeEvent
(QCloseEvent *event)
method in your class definition and add your code into that function. Example:
class foo : public QMainWindow
{
Q_OBJECT
private:
void closeEvent(QCloseEvent *bar);
// ...
};
void foo::closeEvent(QCloseEvent *bar)
{
// Do something
bar->accept();
}
You can attach a SLOT to the
void aboutToQuit();
signal of your QApplication. This signal should be raised just before app closes.
also you can reimplement protected member QWidget::closeEvent()
void YourWidgetWithXButton::closeEvent(QCloseEvent *event)
{
// do what you need here
// then call parent's procedure
QWidget::closeEvent(event);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With