Qt:closeEvent函数不调用的问题
Qt:closeEvent函数不调用的问题
closeEvent函数由事件QCloseEvent触发,所以必须有事件循环的情况下才会触发。此外,closeEvent是顶层窗口才调用。所以:
- 子控件可能不会触发此函数。但如果主动调用close()函数,则会触发closeEvent。
- QDialog一般不会触发closeEvent。QDialog一般调用accept/reject/done结束对话框,但done最终调用hide和close_helper(CloseNoEvent);。如果不调用accept/reject/done,而是通过关闭按钮等方式关闭对话框,是会触发closeEvent,但QDialog的closeEvent还是调用的accept/reject/done函数。所以,QDialog可以重载done函数,以此来替代重载closeEvent函数。
- 主窗口可以重载closeEvent拦截关闭操作。
官方文档描述如下:
This event handler is called with the given event when Qt receives a window close request for a top-level widget from the window system.
By default, the event is accepted and the widget is closed. You can reimplement this function to change the way the widget responds to window close requests. For example, you can prevent the window from closing by calling ignore() on all events.
Main window applications typically use reimplementations of this function to check whether the user’s work has been saved and ask for permission before closing. For example, the Qt Widgets – Application Example uses a helper function to determine whether or not to close the window:
void MainWindow::closeEvent(QCloseEvent *event)
{
if (maybeSave()) {
writeSettings();
event->accept();
} else {
event->ignore();
}
}
转载请注明来源,谢谢。
有偿解决C++编程问题,承接项目定制开发;寻一份全职或兼职Windows C++开发工作。联系邮箱:[email protected]。