1
votes

I have a few dialogs and buttons that call these dialogs. However, every click on the button calls a new dialog window. I want the existing window to close first before the user can click on the button to open another.

Below is an example of a button calling a slot. Whenever I click on the button, it will call a copy of the dialog window. Is there any way to only call one copy of the dialog window only?

Thanks.

Bookmark.cpp:

Bookmark::Bookmark()
{
    createButtons();
    connect(bookmarkButton, SIGNAL(clicked()), this, SLOT(openBookmarkDlg()));
}

void Bookmark::createButtons()
{
    ...

    bookmarkButton = new QToolButton;
    bookmarkButton->setText("Bookmark");
    addWidget(bookmarkButton);

    ...
}

void Bookmark::openBookmarkDlg()
{
    BookmarkDlg *bkDlg = new BookmarkDlg;
    bkDlg->show();
}

Bookmark.h:

class Bookmark : public QToolBar
{
    Q_OBJECT

public:
    Bookmark(void);
    ~Bookmark(void);

public slots:
    void openBookmarkDlg();

private:
    createButtons();
    QToolButton *bookmarkButton;
};
3
Just do not create another instance of dialog in Bookmark::openBookmarkDlg() - Dmitry Sazonov
@DmitrySazonov: Thanks. I moved the new statement to my constructor and now it only opens a single instance of the dialog window. I also edited show() to exec() instead. - Wallace
@Wallace If my answer was helpful, please up vote it. If it solved your problem, please click on the checkbox near it. By doing these things you will be helping future visitors. - karlphillip

3 Answers

0
votes

If you want the dialog window to be modal, i.e. the application doesn't accept user input outside the dialog, use the window modality of the dialog.

Beware however that modal windows can be really annoying to users.

0
votes

If BookmarkDlg inherits QDialog you can do the following:

void Bookmark::openBookmarkDlg()
{
    BookmarkDlg *bkDlg = new BookmarkDlg;

    prepareYourDialog(bkDlg);

    /*If you expect to do something when the dialog is accepted*/
    if (bkDlg->exec() == QDialog::Accepted)
    {
         /*Do something after dialog was accepted, and nothing when canceled*/
    }

    delete bkDlg;
}
0
votes

Convert BookmarkDlg *bkDlg into a variable member of the class, instead of a local variable of the method:

private:
    createButtons();
    QToolButton *bookmarkButton;
    BookmarkDlg *bkDlg;

Then on the implementation of the class, you could do:

void Bookmark::openBookmarkDlg()
{
    if (!bkDlg)
        bkDlg = new BookmarkDlg;

    bkDlg->show();
}