5

我试图在我的实例中MyApplication从继承QApplication或在我的WindowQML实例中继承关闭事件QQuickView。目标是在真正关闭应用程序之前要求确认退出。

在我的应用程序依赖于我在QMainWindow哪里实现这样的closeEvent()方法之前:

// MainWindow inherits from QMainWindow
void MainWindow::closeEvent(QCloseEvent *event)
{
  event->ignore();
  confirmQuit(); // ask for confirmation first
}

问题是我WindowQML继承自的类QQuickView永远不会在方法内部传递closeEvent()。然后我尝试event()像这样重载方法:

// WindowQML inherits from QQuickView
bool WindowQML::event(QEvent *event)
{
  if(event->type() == QEvent::Close)
  {
    qDebug() << "CLOSE EVENT IN QML WINDOW";
  }
}

但这个事件也从未发生过。

我试图采取的下一条道路是MyApplication像这样抓住关闭事件:

// We need to check for the quit event to ask confirmation in the QML view
bool MyApplication::event(QEvent *event)
{
  bool handled = false;

  switch (event->type())
  {
    case QEvent::Close:
      qDebug() << "Close event received";
      event->ignore(); // mandatory?
      handled = true;
      Q_EMIT quitSignalReceived();
      break;

    default:
    qDebug() << "Default event received";
      handled = QApplication::event(event);
      break;
  }

    qDebug() << "Event handled set to : " << handled;
  return handled;
}

信号quitSignalReceived()被正确发出,但事件没有被正确“阻止”,我的应用程序仍然关闭。

所以我有两个问题:

  1. 有没有办法检测QQuickView实例的关闭事件?
  2. 如果不可能,这种MyApplication::event()方式是最好的行动方案吗?为什么我需要在event->ignore()这里打电话?我原以为返回true就足够了。
4

1 回答 1

5

我不知道为什么QWindow没有closeEvent便利事件处理程序。看起来是个错误,遗憾的是在 Qt 6.0 之前无法添加。无论如何,任何 QWindowQCloseEvent在关闭时肯定会得到一个。因此,只需覆盖event并在那里执行您的事件处理。

证明:

  1. QGuiApplication源码
  2. 这个测试程序:

    #include <QtGui>
    
    class Window : public QWindow
    {
    protected:
        bool event(QEvent *e) Q_DECL_OVERRIDE
        {
            int type = e->type();
            qDebug() << "Got an event of type" << type;
            if (type == QEvent::Close)
                qDebug() << "... and it was a close event!";
    
            return QWindow::event(e);
        }
    };
    
    int main(int argc, char **argv) 
    {
        QGuiApplication app(argc, argv);
        Window w;
        w.create();
        w.show();
        return app.exec();
    }
    

    打印这个

    Got an event of type 17 
    Got an event of type 14 
    Got an event of type 13 
    Got an event of type 105 
    Got an event of type 13 
    Got an event of type 206 
    Got an event of type 206 
    Got an event of type 8 
    Got an event of type 207 
    Got an event of type 19 
    ... and it was a close event! 
    Got an event of type 18 
    
于 2013-07-11T22:55:43.047 回答