Using QSettings makes it easy to read and write .ini config files. This note summarizes the most common operations: initialization, reading, writing, deleting, and syncing, useful for quick reference.
Initialization
If you want to work directly with a .ini file, initialize like this:
#include <QCoreApplication>
#include <QSettings>
QString configPath = QCoreApplication::applicationDirPath() + "/config.ini";
QSettings ini(configPath, QSettings::IniFormat);Where:
configPathis the config file pathQSettings::IniFormatmeans using the ini format
Config file example
Assume the config file contains:
[network]
host=127.0.0.1
port=8080
[user]
name=admin
remember=trueReading config
Direct read by path
This is the simplest way to read a single value:
QString host = ini.value("network/host").toString();
int port = ini.value("network/port", 80).toInt();
bool remember = ini.value("user/remember", false).toBool();It is recommended to pass a default value to value(). Then even if the key does not exist, the program still gets a usable result.
Read within a group
If you need to read many items in the same group, using groups is clearer:
ini.beginGroup("user");
QString name = ini.value("name").toString();
bool remember = ini.value("remember", false).toBool();
ini.endGroup();Writing config
setValue() automatically creates a config item if it does not exist.
ini.setValue("network/host", "192.168.1.10");
ini.setValue("network/port", 8080);
ini.beginGroup("user");
ini.setValue("name", "admin");
ini.setValue("remember", true);
ini.endGroup();Deleting config
Delete a single item:
ini.remove("user/name");Delete an entire group:
ini.remove("user");Sync to disk
In most cases, QSettings saves automatically, so you do not need to call a save function.
If you want to write immediately to disk, call:
ini.sync();For example, sync once before program exit or after changing important settings.
Summary
Common QSettings operations are straightforward. Remember these basics:
value()reads configsetValue()writes configremove()deletes configbeginGroup()/endGroup()handles groupssync()writes immediately to disk
For typical desktop app settings, QSettings is usually enough.
No comments yet
Share your thoughts and keep the conversation clear and kind.
Write a comment
Sign in with GitHub first, then you can comment.