Qt如何从哪里找到closeEvent(QCloseEvent*事件)触发

Qt How to find out from where the closeEvent(QCloseEvent *event) fired

本文关键字:QCloseEvent 事件 触发 closeEvent Qt      更新时间:2023-10-16

我的主窗口中有2个触发器1.从关闭应用程序的菜单中2.从忽略并隐藏窗口的窗口X按钮。我正在使用此SIGNAL/插槽我怎么能从哪里知道它被触发了?。

closeEvent:中

connect(ui->actionQuit, SIGNAL(triggered()),this, SLOT(CloseWin()));
void MainWindow::CloseWin()
{
   close();
}
// triggered from the ui->actionQuit amd from the X button
void MainWindow::closeEvent(QCloseEvent *event)
{
    // how can i know from where its bean triggered?     
    hide();
        event->ignore();
}

通过调用QObject::sender()-http://developer.qt.nokia.com/doc/qt-4.8/qobject.html#sender。请注意,只有在对正在调用的SLOT调用此方法时,有效的返回值才可用。

编辑:

如果你将多个信号连接到一个插槽,你还应该考虑使用信号映射器,这在这个QQ中有解释:http://doc.qt.nokia.com/qq/qq10-signalmapper.html

有两种解决方案:

  1. 将菜单项(QAction)信号连接到一个单独的插槽,并在那里调用qApp->quit()
  2. 在插槽中使用sender()方法来确定发送信号的对象

我更喜欢第一个。