我试图捕获一个关闭事件,无论是在我的MyApplication实例继承QApplication还是在我WindowQML继承的实例中QQuickView.目标是在真正关闭应用程序之前要求确认退出.
在我的应用程序依赖于QMainWindow我实现closeEvent()方法的位置之前:
// MainWindow inherits from QMainWindow
void MainWindow::closeEvent(QCloseEvent *event)
{
event->ignore();
confirmQuit(); // ask for confirmation first
}
Run Code Online (Sandbox Code Playgroud)
问题是我WindowQML从继承的类QQuickView永远不会传递给closeEvent()方法.然后我尝试重载这个event()方法:
// WindowQML inherits from QQuickView
bool WindowQML::event(QEvent *event)
{
if(event->type() == QEvent::Close)
{
qDebug() << "CLOSE EVENT IN QML WINDOW";
}
}
Run Code Online (Sandbox Code Playgroud)
但这件事也没发生过.
我试图采取的下一条道路是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;
}
Run Code Online (Sandbox Code Playgroud)
信号quitSignalReceived()正确发射,但事件未被正确"阻止",我的应用程序仍然关闭.
所以我有两个问题:
QQuickView的实例?MyApplication::event()这样的行动最好的办法?为什么我需要在event->ignore()这里打电话?我本来以为回来true就足够了.我不知道为什么QWindow没有closeEvent便利事件处理程序.看起来像是一个错误,遗憾的是它无法在Qt 6.0之前添加.无论如何,任何QWindow肯定会QCloseEvent在它关闭时获得.因此,只需覆盖event并执行您的事件处理.
样张:
这个测试程序:
#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();
}
Run Code Online (Sandbox Code Playgroud)
打印这个
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
Run Code Online (Sandbox Code Playgroud)