【发布时间】:2022-01-07 17:03:53
【问题描述】:
以下代码 sn -p 打开两个窗口,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();
}
编辑就我而言,这两个小部件设计在两个独立的库中,因此它们无法相互通信。因此,关闭事件不适用。
编辑最终我对我的问题的解决方案是基于@JeremyFriesner 的回答:在closeEvent 的w1 中发出closed 信号,然后连接它(而不是QObject::destroyed ) 到w2。
【问题讨论】:
-
我认为
Destroyed信号仅在对象超出范围并释放其内存时才会发生,这会在main返回时发生。 -
基本的调试调查包括将其他东西连接到该信号并设置断点或输出消息,以查看它是否真的被触发了。
-
@DavidGrayson 谢谢。不幸的是,这无法回答我的问题。
-
我看到的所有文献和类似的问答结果都有相同的答案:处理
closeEvent。