这个问题看起来非常简单,但是我想在 QMainWindow
关闭时转储一些数据,因此我使用了以下代码:
QObject::connect(MainWindow.centralwidget, SIGNAL(destroyed()), this, SLOT(close()));
但是这似乎并没有使它调用close()
。我做错了吗?
centralwidget难道不应该被销毁吗?
或者说应用程序在close()
被调用之前就关闭了?
还有其他的方法吗?
您最好在主MainWindow
类中重新实现一个虚函数,如下所示:
class MainWindow : public QMainWindow {
Q_OBJECT;
public:
MainWindow();
protected:
void closeEvent(QCloseEvent *event);
}
然后在源文件中声明:
void MainWindow::closeEvent(QCloseEvent *event) {
// do some data saves or something else
}
祝您好运。
closeEvent()
实现通常会根据是否存在未保存的更改而调用 event.accept()
或 event.ignore()
。通常不会调用 QMainWindow::closeEvent(event)
。参见 closeEvent()
文档 获取另一个有用的示例。 - Cecil Curry我会尝试使用QGuiApplication::lastWindowClosed()替代。
在Python中(使用pyqt4或pyqt5),您需要执行以下操作:
class MyWindow(QMainWindow):
def __init__(self):
super(MyWindow, self).__init__()
#
# My initializations...
#
''''''
def closeEvent(self, *args, **kwargs):
#
# Stuff I want to do when this
# just before (!) this window gets closed...
#
''''''
有趣的是,closeEvent(..) 函数中的内容会在窗口关闭之前执行。您可以使用以下测试进行验证:
# Test if the closeEvent(..) function
# executes just before or just after the window closes.
def closeEvent(self, *args, **kwargs):
# 'self' is the QMainWindow-object.
print(self)
print(self.isVisible())
# Print out the same stuff 2 seconds from now.
QTimer.singleShot(2000, lambda: print(self))
QTimer.singleShot(2100, lambda: print(self.isVisible()))
''''''
<myProj.MyWindow object at 0x000001D3C3B3AAF8>
True
<myProj.MyWindow object at 0x000001D3C3B3AAF8>
False
QMainWindow::closeEvent(QCloseEvent *)
。然后实现一个名为 closing()
的新信号,并从 QMainWindow::closeEvent()
的实现中发射它。然后,您可以连接到该信号以在窗口关闭之前执行某些操作。您还可以直接使用 closeEvent
来做您需要做的事情,比如保存状态、同步数据或其他。你的初始问题和代码不匹配。如果你想在 QMainWindow
上做一些事情,可以创建一个子类并重新实现 closeEvent
或连接到 MainWindow::destroyed()
。但是请注意第三段的说明。
但是你的代码显示了一个似乎是第三个类的东西,它将 MainWindow
的子项连接到某个名为 close()
的插槽上。 centralwidget
将在 MainWindow 被销毁后被销毁,所以这很可能对你没有帮助。
此外,这取决于你如何创建 MainWindow(堆栈或堆)以及是否正确地销毁它。理想情况下,你应该创建一个 QMainWindow
的子类(如果你使用了设计器,你可能已经有了)。
在你的主窗口析构函数中加入dump代码怎么样?
this
在你的QObject
层次结构中的位置是什么?可能会在信号发送之前被删除。当然,我不会太担心它,因为到目前为止给出的答案中有更好的替代方案。 - Troubadour