Qt:如何在用户关闭的另一个 window 上关闭 window
Qt: how can one close a window upon another window closed by the user
以下代码片段打开两个 windows,w1 和 w2。当用户关闭 w1 时,如何强制 w2 关闭?如评论中所述,connect
函数无法正常工作。
#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 在我的例子中,这两个小部件是在两个独立的库中设计的,因此它们无法相互通信。因此,关闭事件不适用。
编辑 最终,我对问题的解决方案是基于@JeremyFriesner 的回答:在 closeEvent
of w1
中发出 closed
信号],并将此(而不是 QObject::destroyed
)连接到 w2
。
您的程序的这个修改版本显示了如何通过覆盖 w1
小部件上的 closeEvent(QCloseEvent *)
方法来做到这一点:
#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();
}
如果你想做得更优雅,你可以让你的 closeEvent()
方法覆盖发出一个信号,而不是调用指针上的方法;这样你就不会在两者之间有直接的依赖关系类,这会给你未来更大的灵活性。
以下代码片段打开两个 windows,w1 和 w2。当用户关闭 w1 时,如何强制 w2 关闭?如评论中所述,connect
函数无法正常工作。
#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 在我的例子中,这两个小部件是在两个独立的库中设计的,因此它们无法相互通信。因此,关闭事件不适用。
编辑 最终,我对问题的解决方案是基于@JeremyFriesner 的回答:在 closeEvent
of w1
中发出 closed
信号],并将此(而不是 QObject::destroyed
)连接到 w2
。
您的程序的这个修改版本显示了如何通过覆盖 w1
小部件上的 closeEvent(QCloseEvent *)
方法来做到这一点:
#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();
}
如果你想做得更优雅,你可以让你的 closeEvent()
方法覆盖发出一个信号,而不是调用指针上的方法;这样你就不会在两者之间有直接的依赖关系类,这会给你未来更大的灵活性。