Cannot get QSettings to read from custom storage format

1.6k views Asked by At

I'm trying to create a custom format for QSettings, but I can't get it to read from the storage.

In the code below, if I run settings.setValue("test", 123"), it correctly calls the write function and prints Calling writeSqlite. However, if I try settings.value("test"), it doesn't call the read function and doesn't print Calling readSqlite.

Any idea what could be the issue?

bool readSqlite(QIODevice &device, QSettings::SettingsMap &map) {
    qDebug() << "Calling readSqlite";
    return true;
}

bool writeSqlite(QIODevice &device, const QSettings::SettingsMap &map) {
    qDebug() << "Calling writeSqlite";
    return true;
}

void Settings::initialize() {
    const QSettings::Format SqliteFormat = QSettings::registerFormat("sqlite", &readSqlite, &writeSqlite);
    QSettings::setDefaultFormat(SqliteFormat);

    QSettings settings;
    // This doesn't work:
    // qDebug() << settings.value("test");

    // This works:
    // settings.setValue("test", 123456);
}
2

There are 2 answers

11
Mike On BEST ANSWER

QSettings does not call the custom read function (readSqlite in your case) unless the settings file is readable and has a non-zero size (obviously, It does not need to call it if these conditions are not met). See source code here.

Since your custom write function does not really write anything to device, your settings file is left empty, and readSqlite is not called.

If you want to see your readSqlite function getting called, you can add some arbitrary data to your settings file, or maybe add some device.write() call in your writeSqlite implementation, and your readSqlite function will get called in the next run.

3
laurent On

Based on Mike's answer, this is the solution I went for. Not pretty but it works:

bool readSqlite(QIODevice &device, QSettings::SettingsMap &map) {
    // Read the map from SQL database
    return true;
}

bool writeSqlite(QIODevice &device, const QSettings::SettingsMap &map) {
    device.write("X", 1); // HACK - required to get readSqlite to work
    // Write the map to SQL database
    return true;
}

void Settings::initialize() {
    const QSettings::Format SqliteFormat = QSettings::registerFormat("sqlite", &readSqlite, &writeSqlite);
    QSettings::setDefaultFormat(SqliteFormat);
}