Is there a way to do this automatically?
Yes and no.
You could run qmake like this:
qmake -project "QT+=widgets"
and then it is generated properly, but other than that from the command line, no. Also, note that you would like to use a guard if you plan to support Qt 4, too:
greaterThan(QT_MAJOR_VERSION, 4):QT+=widgets
If you happen to use QtCreator
, you will be able to avoid all this as the IDE will generate this all for you automatically.
Also, you should be able to avoid including the whole module with all the classes even though you do not use them all. So, instead of writing this:
#include <QtWidgets>
You could write:
#include <Foo>
#include <Bar>
...