title: QtQuick: how to override window close event?
body: <p>My experience in Qt is about two weeks, excuse me if I happen to ask a stupid question.</p>
  
  <p>My program uses QtQuick-based GUI. I initialise it in my <em>main.cpp</em></p>
  
  <pre><code>#include &lt;QGuiApplication&gt;
  #include &lt;QtQuick/QQuickView&gt;
  
  #include "VeryVeryImportantItem.h"
  
  extern
  int main(int argc, char * argv[])
  {
      qmlRegisterType&lt;VeryVeryImportantItem&gt;("com.my.stuff", 1, 0, "VeryVeryImportantItem");
  
      QQuickView      quickView(QUrl("MyView.qml"));
  
      quickView.show();
  
      QGuiApplication app;
  
      return app.exec();
  }
  </code></pre>
  
  <p>And <em>MyView.qml</em> looks like this:</p>
  
  <pre><code>import QtQuick 2.1
  import QtQuick.Window 2.1
  import com.my.stuff 1.0
  
  Item VeryVeryImportantItem {
      id : veryVeryImportantItem
      ...
  }
  </code></pre>
  
  <p>And <em>VeryVeryImportantItem.h</em> is as follows:</p>
  
  <pre><code>#include &lt;QtQuick/QQuickItem&gt;
  
  class VeryVeryImportantItem : public QQuickItem
  {
      Q_OBJECT
  public:
      Q_INVOKABLE void cleanup();
      ...
  };
  </code></pre>
  
  <p>And now the problem. <strong>How do I intercept close event on my root window/view, call VeryVeryImportantItem::cleanup(); and only after that close the application?</strong></p>
  
  <p>What I've found out by now is that <code>QQuickItem::window()</code> can give me the pointer to the window I need and that the window has signal <code>QQuickWindow::closing(QQuickCloseEvent *);</code> and that in theory I can prevent the window from closing by manipulating the given <code>QQuickCloseEvent</code> object. <strong>But it's not public, I don't have access to its methods!</strong></p>
  
  <p>Ok. Another way might be that I could do something similar from QML. QML type <code>QWindow</code> has <code>closing(CloseEvent)</code> signal and if I set <code>CloseEvent.accepted</code> false in a slot connected to it that would prevent the window from immediate closing and enable me to call <code>veryVeryImportantItem.cleanup()</code> method. But then I have another problem: how do I get the reference to my root window if I've created it not in QML but in C++ start-up code.</p>
  
  <p>I guess this is the very common situation and there obviously ought to be a well-defined way to handle this but I've been googling for some four hours and still haven't found any decent explanation.</p>