Question

I'm a beginner in programming in C++/Qt. I created a widget called wexample in Qt. When displayed, there is an button event that will open another window of the same widget wexample, and so on. My question is how to close all the windows of that widget?

I open my first widget as follows:

wexample *w = new wexample;
w-> show();

Inside the widget, I also have these events:

void wexample::on_pushButton1_clicked()
{
wexample *w = new wexample;
w -> show();
}
void wexample::on_pushButton2_clicked()
{
QWidget::close();
}

So when button 1 is pressed, it will open a new window and so on. When button 2 is pressed, it will close the window where the button is. Is there a way to close all of the windows from that widget all at once? Or even better, is there a way to close specific windows (for example, all the windows after the 3rd one)?

I have tried using signal and slot but I can't connect them since they are all of the same name. I would have to declare all of the widgets beforehand for it to work but I cannot know how many of them the user will need.

I'm sorry if my question isn't clear. I am really a beginner and have been searching for a while but couldn't find an answer. Maybe the structure as a whole doesn't make sense. Please help. Thanks.

Was it helpful?

Solution

You should add your newly created wexample's to a list and then iterate through them when you'd like to close them:

class wexample : public QDialog
{
...

private Q_SLOTS:
    void on_pushButton1_clicked() {
        wexample *w = new wexample(this);
        m_wexamples.append(w);
        w->show();
    }

    void wexample::on_pushButton2_clicked() {
        foreach (wexample *w, m_wexamples)
            w->close();
    }

private:
    QList<wexample*> m_wexamples;
};

A few extra points here:

  • Notice that I added (this) to the wexample constructor above. This ensures that the dialog is properly parented (and therefore will be cleaned up if you don't manually delete the object yourself). Previously, you would have been leaking memory every time you showed the dialog

  • The slot for the second button simply iterates through the list of dialogs and closes them. This does NOT mean that the dialogs have been deleted (and in fact are still in the list after closing them). If you'd prefer to fully remove them, then use of the "take" methods of QList, removing the dialog from the list and then call dialog->close(); dialog->deleteLater(); on it

  • This is a somewhat contrived example, you probably won't be opening the dialog from within the dialog's implementation in practice

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top