Home > front end >  Qt: how can one close a window upon another window closed by the user
Qt: how can one close a window upon another window closed by the user

Time:12-01

The following code snippet opens two windows, w1 and w2. How can one force w2 to close when w1 is closed by the user? As in the comment, the connect function is not working that way.

#include <QApplication>
#include <QtGui>
#include <QtCore>
#include <QtWidgets>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QWidget w1;
    w1.setWindowTitle("w1");
    w1.show();

    QWidget w2;
    w2.setWindowTitle("w2");
    w2.show();

    // when w1 is closed by the user, I would like w2 to close, too.
    // However, it won't happen, even though the code compiles fine.
    QObject::connect(&w1, &QObject::destroyed, &w2, &QWidget::close);

    return a.exec();
}

Edit In my case, those two widgets are designed in two separate libraries, so they cannot communicate with each other. Thus, the close event is not applicable.

CodePudding user response:

This modified version of your program shows how you could do it by overriding the closeEvent(QCloseEvent *) method on your w1 widget:

#include <QApplication>
#include <QtGui>
#include <QtCore>
#include <QtWidgets>

class MyWidget : public QWidget
{
public:
   MyWidget(QWidget * closeHim) : _closeHim(closeHim)
   {
      // empty
   }

   virtual void closeEvent(QCloseEvent * e)
   {
      QWidget::closeEvent(e);
      if (_closeHim) _closeHim->close();
   }

private:
   QWidget * _closeHim;
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QWidget w2;
    w2.setWindowTitle("w2");
    w2.show();

    MyWidget w1(&w2);
    w1.setWindowTitle("w1");
    w1.show();

    return a.exec();
}

If you wanted to do it more elegantly, you could have your closeEvent() method-override emit a signal instead of calling a method on a pointer; that way you wouldn't have a direct dependency between the two classes, which would give you more flexibility in the future.

  •  Tags:  
  • c qt
  • Related