Please instantiate the QApplication object first

19.9k Views Asked by At

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!

2

There are 2 best solutions below

3
On BEST 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.

1
On

QApplication derives from QCoreApplication.
As you can see from the sources, applicationDirPath is defined as:

QString QCoreApplication::applicationDirPath()
{
    if (!self) {
        qWarning("QCoreApplication::applicationDirPath: Please instantiate the QApplication object first");
        return QString();
    }

    // ... more code
}

By going deeper into the code, we find that self is initialized by the init function, that is invoked by the constructor.
Because of that, it looks to me that it won't work as you expect it to do unless you have explicitly created an instance of a Q*Application class (in this case, an instance of QApplication).

Note from the documentation above that it is suggested to create such a class as soon as possible:

In general, we recommend that you create a QCoreApplication, QGuiApplication or a QApplication object in your main() function as early as possible. exec() will not return until the event loop exits; e.g., when quit() is called.

It means even before you try to access to QApplication::applicationDirPath(), of course.
Otherwise you won't be able to get the right path from that method while using QSettings.