Reputation: 293
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();
}
}
Upvotes: 0
Views: 824
Reputation: 12901
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();
}
}
Upvotes: 1