Skip to content

Instantly share code, notes, and snippets.

@vastus
Last active January 3, 2018 06:22
Show Gist options
  • Save vastus/3496995 to your computer and use it in GitHub Desktop.
Save vastus/3496995 to your computer and use it in GitHub Desktop.
Modal dialog for confirming the user to close the window in Qt

Confirm dialog in Qt

Compiling

Run the following commands from the project dir:

$ qmake -project && qmake && make
#include <QApplication>
#include "widget.cpp"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Widget widget;
widget.show();
return app.exec();
}
#include "widget.h"
Widget::Widget(QWidget *parent) : QWidget(parent)
{
label = new QLabel(tr("Try to close this window"), this);
setWindowTitle(tr("Filename: README.txt [*]"));
setWindowModified(true);
}
void Widget::closeEvent(QCloseEvent *event)
{
if (Widget::closeWindow())
event->accept();
else
event->ignore();
}
bool Widget::closeWindow()
{
if (!isWindowModified())
return true;
QMessageBox::StandardButton answer = QMessageBox::question(
this,
tr("Close the Window"),
tr("Do you want to close the window?"),
QMessageBox::Yes | QMessageBox::No
);
return answer == QMessageBox::Yes;
}
#ifndef WIDGET_H
#define WIDGET_H
#include <QtGui>
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = 0);
protected:
void closeEvent(QCloseEvent *event);
private:
bool closeWindow();
QLabel *label;
};
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment