To explain a bit more. QApplication object is always available in your application through the static QCoreApplication::instance() call (or qApp macro), making it a good placeholder for objects, which otherwise would need to be global. This gives an additional benefit, because sometimes when you construct some global objects (for example timers), you get a message, that you can't construct such an object without a QApplication object. This is a way to bypass such messages.
The main window object should only hold data related to the main window itself, whereas the application object can hold data related to different components of the application. To go a little further, the application object can wrap the main window object too, which could make the resulting code clearer and simpler, look at an example of a main() function with the main window (be it QMainWindow or any other widget) wrapped into the application:
#include "myapplication.h"
int main(int argc, char **argv){
MyApplication app;
return app.exec();
}
#include "myapplication.h"
int main(int argc, char **argv){
MyApplication app;
return app.exec();
}
To copy to clipboard, switch view to plain text mode
You can also implement your application object to return various objects used by different components as static pointers, for example a pointer to the main window. This makes access to the widgets you need simpler and less error prone. Consider this snippet:
MyWidget *wid = qobject_cast<MyWidget*>(parent()->parent()->parent()->parent());
MyWidget *wid = qobject_cast<MyWidget*>(parent()->parent()->parent()->parent());
To copy to clipboard, switch view to plain text mode
This could be substituted by:
MyWidget *wid = MyApplication::myWidget();
MyWidget *wid = MyApplication::myWidget();
To copy to clipboard, switch view to plain text mode
or even as a regular function call - without static pointers (some people don't like them):
MyWidget *wid = qApp->myWidget();
MyWidget *wid = qApp->myWidget();
To copy to clipboard, switch view to plain text mode
To summarise, in my opinion you can put in the application object everything you consider "application wide" and in the main window only those things, which are actually used by the main window or its direct subclasses. A different approach comes when ypu are lazy -- you put everything in the main window and use QApplication without subclassing, as it is a little more time consuming to make a good design out of it.
Bookmarks