在关闭QQuickView或QApplication之前询问确认

时间:2013-07-11 12:09:08

标签: qml qt5 qtquick2

我试图在继承自MyApplication的{​​{1}}实例或继承自QApplication的{​​{1}}实例中捕获一个关闭事件。目标是在真正关闭申请之前要求确认退出。

在我的申请依赖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正确发出,但事件没有被“阻止”,我的申请仍然关闭。

所以我有两个问题:

  1. 有没有办法检测// 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; } 实例的结束事件?
  2. 如果不可能,quitSignalReceived()方式是最好的行动方式吗?为什么我需要在这里拨打QQuickView?我原本以为返回MyApplication::event()就够了。

1 个答案:

答案 0 :(得分:5)

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

证明:

  1. QGuiApplication source code
  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