问题
I'm having trouble binding an "On Close" event for my application written in QtQuick. What I'd like to do is do the standard "confirm exit" method and maybe I'm going about this the wrong way.
As I understand it I want something like
void MainDriver::onClose(QEvent* event)
{
if(notSaved)
{
//prompt save
event->ignore();
}
else
event->accept();
}
however it seems QQuickCloseEvent isn't derived from QEvent or I'm including the wrong header (very possible) and I can't find out where it is defined so that I can connect the signals.
Is there a better way to get around this? Right now I instantiate the main window like this:
QQmlApplicationEngine engine; //Actually initialized in the constructor
engine.load(QUrl("qrc:/qml/Window.qml"));
QObject *topLevel = engine.rootObjects().value(0);
QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel);
I'm using ApplicationWindow (QtQuick Controls) as the main window which is derived from QWindow. I'm open to suggestion here, I'd like to stick to QtQuick and not wrap everything in a standard QWindow or QMainWindow, but maybe that's a poor route to take. Any help would be appreciated.
回答1:
You can use EventFilter to handle close event in main window's controller:
class MyEventFilter : public QObject
{
Q_OBJECT
protected:
bool eventFilter(QObject *obj, QEvent *event);
};
bool MyEventFilter::eventFilter(QObject *obj, QEvent *event)
{
if (event->type() == QEvent::Close)
{
// TODO: confirm
return true;
} else
{
// standard event processing
return QObject::eventFilter(obj, event);
}
}
And in your main():
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
MyEventFilter filter;
QtQuick2ApplicationViewer viewer;
viewer.installEventFilter(&filter);
viewer.setMainQmlFile(QStringLiteral("qml/QCloseConfirm/main.qml"));
viewer.showExpanded();
return app.exec();
}
Here is example. But it doesn't seem to be perfect. There should be a better solution.
来源:https://stackoverflow.com/questions/19502338/qtquick2-cant-connect-applicationwindow-closing-signal-to-method-c-novice