0

I have a checkable pushbutton set to exec/close a dialog widget that I have created.

My idea is when the pushbutton is checked, it will close the dialog widget. If it's not checked, it should open the dialog widget. But I am unable to get it to work. It keeps on opening instances of the dialog widget. I wanted to open one instance of the dialog widget only. Could anyone please help?

MainDlg::MainDlg()
{
    connect(dialogButton, SIGNAL(clicked()), this, SLOT(setDialog()));
}

void MainDlg::setDialog()
{
   SetDialogDlg setDlg;
   if(dialogButton->isChecked())
   {
      setDlg.close();
   }
   else
   {
      setDlg.exec();
   }
}
Wallace
  • 293
  • 1
  • 9
  • 18

1 Answers1

1

There are a few things that are wrong in your code. First thing is, your SetDialogDlg object will only exist inside your MainDlg::setDialog() function. Once this function finishes your SetDialogDlg object will be destroyed.

Then you are creating a new instance of SetDialogDlg every time MainDlg::setDialog() function is called. And you are trying to close a dialog that hasn't been shown yet.

Then there is a problem with setDlg.exec(). This is a blocking function. So you shouldn't even be able to push your dialogButton once the dialog has been shown.

To solve these problems you should have a member variable in your MainDlg class.

//maindlg.h
...
public:
   SetDialogDlg *myDialog;
...

 

//maindlg.cpp
MainDlg::MainDlg()
{
   ...
   myDialog = new SetDialogDlg(this);
   ...
}

  Then inside your MainDlg::setDialog() function, call QWidget::show() instead of QDialog::exec().

void MainDlg::setDialog()
{
   if(dialogButton->isChecked())
   {
      myDialog->close();
   }
   else
   {
      myDialog->show();
   }
}
thuga
  • 12,601
  • 42
  • 52
  • Thanks thuga! It works right now. However, it works for the first time. I clicked on the button, it shows. The next click hides the dialog to the background. But the following click does not show the dialog. Is it something to do with my if-else statement? – Wallace Sep 20 '13 at 07:40
  • 1
    @Wallace It should work. I tested the code with the same `if` statement and it works fine. You can use [QDebug](http://qt-project.org/doc/qt-5.0/qtcore/qdebug.html) class to check if the `if` statements are working OK. Just add `qDebug() << "inside if";` inside the `if` statement and `qDebug() << "inside else;` inside the `else` statement. Remember to include the header: `#include ` – thuga Sep 20 '13 at 07:51
  • Sorry @thuga. My mistake. I solved it. Thanks a bunch! :) Do you have any idea how to do a slide-in/slide out or fade effect? (Suppose I have a right toolbar. I click on the button on the toolbar, the dialog widget will have a "slide-out" effect from the toolbar. When I click on the button again, the dialog widget will "slide-in" to the toolbar) – Wallace Sep 20 '13 at 07:54
  • 1
    @Wallace See QPropertyAnimation. – thuga Sep 20 '13 at 07:59