【发布时间】:2013-07-11 12:09:08
【问题描述】:
我试图在继承自 QApplication 的 MyApplication 实例或从 QQuickView 继承的 WindowQML 实例中捕获关闭事件。目标是在真正关闭应用程序之前要求确认退出。
在我的应用程序依赖 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() 被正确发出,但事件没有被正确“阻止”,我的应用程序仍然关闭。
所以我有两个问题:
- 有没有办法检测
QQuickView实例的关闭事件? - 如果不可能,
MyApplication::event()方式是不是最好的做法?为什么我需要在这里打电话给event->ignore()?我原以为返回true就足够了。
【问题讨论】:
-
刚刚发现,你不应该忽略,而是接受关闭事件(至少在 Mac OS X 上),这就是我觉得有趣的地方