Pregunta

I am trying to use a QSettings object with an IniFormat for UserScope settings loaded at the start of the application. I moved the QSettings setup code into a separate method and call it from main() as shown in this snippet:

#include <QDebug>
#include <QSettings>
#include <QStringList>

void loadSettings()
{
    qDebug() << "[BEGIN] loadSettings()";

    QCoreApplication::setOrganizationName("Org");
    QCoreApplication::setApplicationName("App");

    QSettings settings(QSettings::IniFormat,
                       QSettings::UserScope,
                       "Org",
                       "App");

    settings.setValue("TheAnswer", "42");

    QStringList keys = settings.allKeys();
    qDebug() << "Loaded " << keys.size() << " keys.";

    qDebug() << "[END] loadSettings()";
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    loadSettings();

    QSettings settings;
    QStringList keys = settings.allKeys();
    qDebug() << "Settings has " << keys.size() << " keys.";

    // Empty
    qDebug() << settings.value("TheAnswer").toString();

    return a.exec();
}

The resulting output is:

[BEGIN] loadSettings()
Loaded 1 keys.
[END] loadSettings()
Settings has 0 keys.
""

Looking at the documentation for QSettings, it states that the usage of QCoreApplication to set the organization name and application name would allow the usage of the convenience QSettings creation method from anywhere in the application, so my understanding is that the code snippet should be able to access the value stored with key "TheAnswer" that was loaded by the loadSettings() method. Yet, when I create a new QSettings object using the convenience method, it has no key/value pairs. I verified the ini file is created and has correct data. What am I missing?

¿Fue útil?

Solución

I believe the problme is that default format is QSettings::NativeFormat instead of QSettings::IniFormat, which you are using.

I noticed that there's a static QSettings::setDefaultFormat() function, so I would try adding this to your loadSettings() function:

QSettings::setDefaultformat( QSettings::IniFormat );

Also, once you've set the application/organization and default format, I don't think you need to pass any arguments to the QSettings constructor in your loadSettings() function.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top