Wednesday, June 8, 2011

Reimplementing closeEvent of QDialog

It is always required to ask the user before closing the dialog whether he/she is sure about that. closeEvent event handler can also be used to save the position of the dialog before it is being closed. closeEvent of QDialog is being called before than the destructor of the extended QDialog instance.
Sample extended QDialog shows a QMessageBox instance when the user clicks on the close button that is placed at the top right corner of the dialog and asks for confirmation before closing the dialog. Depending on the user’s selection, dialog closes or stays open.
Sample project started as a QT Gui Application and contains main.cpp, QDialogCloseEvent.h and QDialogCloseEvent.cpp files.
Project Directory Structure in Qt Creator IDE :

QDialogCloseEvent.pro is the project configuration file and contains:
QT       += core gui
TARGET    = QDialogCloseEvent
TEMPLATE  = app
SOURCES  += main.cpp\
         QDialogCloseEvent.cpp
HEADERS  += QDialogCloseEvent.h

main.cpp file contains the custom QDialog instance and shows it.
#include <QApplication>
#include "QDialogCloseEvent.h"
int main(int argc, char *argv[]) {
    QApplication a(argc, argv);
    Dialog w;
    w.show();
    return a.exec();
}

QDialogCloseEvent.h file is the extended QDialog class header file.
#ifndef QDIALOGCLOSEEVENT_H
#define QDIALOGCLOSEEVENT_H
#include <QDialog>
class Dialog : public QDialog
{
    Q_OBJECT
public:
    Dialog(QWidget *parent = 0);
    ~Dialog();
protected:
    void closeEvent(QCloseEvent * event);
};
#endif // QDIALOGCLOSEEVENT_H

QDialogCloseEvent.cpp file contains implementation details for extended QDialog class.
#include "QDialogCloseEvent.h"
#include <QMessageBox>
#include <QCloseEvent>
Dialog::Dialog(QWidget *parent) : QDialog(parent)
{
    resize(300,90);
}
Dialog::~Dialog(){}
void Dialog::closeEvent(QCloseEvent *event)
{
    QMessageBox msgBox;
    msgBox.setText("Are you sure you want to close?");
    msgBox.setStandardButtons(QMessageBox::Close | QMessageBox::Cancel);
    msgBox.setDefaultButton(QMessageBox::Close);
    int result = msgBox.exec();
    switch (result) {
      case QMessageBox::Close:
          event->accept();
          break;
      case QMessageBox::Cancel:
          event->ignore();
          break;
      default:
          QDialog::closeEvent(event);
          break;
    }
}

Custom QDialog with QMessageBox:

Application created by QT Creator and uses Qt4.7 .

2 comments:

  1. its been helpfull for me dude, more than on year later.

    ReplyDelete
  2. Many thanks. Really helpful example.

    ReplyDelete