Bri Bri
Bri Bri

Reputation: 2204

Using QSettings with data stored in a QByteArray, or QIODevice?

I have data in ini format that was originally written using QSettings (and so it contains some QSettings-specific syntax) that is stored in a QByteArray. I'd like to be able to read and write to it using QSettings. Unfortunately, out of the box QSettings only seems capable of working with files specifically, and can't be used with a QByteArray or an instance of a class that derives from QIODevice such as QBuffer.

So far, I've found only one way of dealing with this: dump the data temporarily into a file, probably using QTemporaryFile, and read that using QSettings

However, I'd like to avoid writing this data to disk if at all possible. Ten years have gone by since that old thread was posted. Is there a better method available now?

I had tried using QAbstractFileEngine even though it's private in Qt 5, but then later discovered that QAbstractFileEngine in conjunction with QSettings only works for reading settings. Writing settings using QSettings unfortunately always assumes the file is a native file. So (as of November 2024) I am still using a temporary file to do this.

This is not a debugging question and I have no idea why it was closed for lacking debugging details, and as such it makes no sense to require a minimal example. This is asking about how to accomplish a specific goal in a specific API. If I could produce a minimal example, I wouldn't be asking the question!

Upvotes: 1

Views: 1024

Answers (1)

JarMan
JarMan

Reputation: 8277

I think you can achieve what you want by registering your own format. You provide your own read/write functions, so you can do anything you want inside them. The docs provide an example for using an XML format. You can easily modify this to write into a QByteArray.

// Buffer to store settings
QByteArray someBuffer;

bool readSettingsFromBuffer(QIODevice &device, QSettings::SettingsMap &map)
{
    // Ignore "device" and read from someBuffer instead.
}

bool writeSettingsToBuffer(QIODevice &device, const QSettings::SettingsMap &map)
{
    // Ignore "device" and write to someBuffer instead.
}

int main(int argc, char *argv[])
{
    const QSettings::Format BufferFormat =
            QSettings::registerFormat("buffer", readSettingsFromBuffer, writeSettingsToBuffer);

    QSettings settings(BufferFormat, QSettings::UserScope, "MyCompany",
                       "MyApplication");

    ...
}

Upvotes: 1

Related Questions