Please instantiate the QApplication object first

honiahaka10 picture honiahaka10 · Aug 19, 2016 · Viewed 13.4k times · Source

I have a static class and want it to have static QSettings. But with my initialization I get a warning:

QSettings* MySQLConnection::settings = new QSettings(QApplication::applicationDirPath() + "/config.ini", QSettings::IniFormat);

QCoreApplication::applicationDirPath: Please instantiate the QApplication object first

As a workaround I initialize the QSetting manually at the beginning of my main function. Is there any better way to initialize my static member?

Thank you!

Answer

Ideally, you should have no static class instances of any sort. Singletons should have a local instance in main() and their static methods should forward through an instance pointer to regular methods. See how QCoraApplication does it for a good example.

In any case, a QSettings instance can be ephemeral. It's only a handle to the settings mechanism. Not much point in making it static or keeping it around. It's normal to have QSettings as a local variable in a function.