0

I have been trying to hide a stand alone dialog application when the user hits the typical close button (The one with the X in the corner usually next to the minimize button) I cam across this post:

Qt: How do I handle the event of the user pressing the 'X' (close) button?

which I thought would have my solution, but I get strange behavior when I implement it.

void MyDialog::reject()
{
    this->hide()
}

When I hit the X Button the whole application closes (the process disappears) which is not what I want. Since my gui spawns with a command line, I setup a test system where I can tell my dialog to hide via a text command where I call the same 'this->hide()' instruction, and everything works fine. The dialog hides and then shows back up when I tell it to show.

Any ideas why the reject method is closing my app completely even when I don't explicitly tell it to?

Community
  • 1
  • 1
MrJman006
  • 752
  • 10
  • 26

1 Answers1

0

Override the virtual function "virtual void closeEvent(QCloseEvent * e)" in your dialog class. The code comment will explain in detail.

Dialog::Dialog(QWidget *parent) :QDialog(parent), ui(new Ui::Dialog){
    ui->setupUi(this);
}
Dialog::~Dialog(){
    delete ui;
}
//SLOT
void Dialog::fnShow(){
    //Show the dialog
    this->show();
}
void Dialog::closeEvent(QCloseEvent *e){
    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){
        //Hiding the dialog when the close button clicked
        this->hide();
        //event ignored
        e->ignore();
        //Testing. To show the dialog again after 2 seconds
        QTimer *qtimer = new QTimer(this);
        qtimer->singleShot(2000,this,SLOT(fnShow()));
        qtimer->deleteLater();
    }
    //below code is for understanding
    //as by default it is e->accept();
    else{
        //close forever 
        e->accept();
    }
}
Jeet
  • 1,006
  • 1
  • 14
  • 25
  • I came across this earlier and when I implemented this on my QDialog but just with the e->ignore() line for a quick test and my dialog stopped responding to clicks on the X. Let me retry it and double check. – MrJman006 Feb 02 '16 at 22:15
  • well for whatever reason, this works now for me. Thanks for the help! – MrJman006 Feb 02 '16 at 22:26