QSetttings IniFormat 最终出现在注册表中

QSetttings IniFormat ends up in Registry

我正在将应用程序数据保存在 Ini 文件中。方法如下:

QSettings IniFile(K_COMPNAME,K_INIFILENAME);
QSettings::setDefaultFormat(QSettings::IniFormat);
IniFile.setValue("Location",loc);
IniFile.setValue("BaudRate",baud);
IniFile.sync();

K_INIFILENAME 是常数 "Settings".

我希望 Settings.ini 与我的 exe 位于同一文件夹中。 但不是。相反,它保存在注册表中。因为当我这样做 qDebug() << IniFile.fileName(); 它 returns:

"\HKEY_CURRENT_USER\Software\MyCompany\Settings"

我的问题是为什么会这样,以及如何将其保存在ini文件中。

QSettings 构造函数的 documentation 指出:

Use setDefaultFormat() before calling this constructor to change the default format used by this constructor.

因此,在创建 QSettings 对象之前调用 setDefaultFormat

QSettings::setDefaultFormat(QSettings::IniFormat);
QSettings IniFile(K_COMPNAME,K_INIFILENAME);
IniFile.setValue("Location",loc);
IniFile.setValue("BaudRate",baud);
IniFile.sync();

请记住,对于构造函数:

QSettings IniFile(K_COMPNAME,K_INIFILENAME);

Constructs a QSettings object for accessing settings of the application called application from the organization called organization,

The scope is set to QSettings::UserScope, and the format is set to QSettings::NativeFormat (i.e. calling setDefaultFormat() before calling this constructor has no effect).

这意味着它是一个注册表有效构造函数(在 windows 下).. INI 格式的正确方法是:

QCoreApplication::setOrganizationName(K_COMPNAME);
QCoreApplication::setApplicationName(K_INIFILENAME);
QSettings::setDefaultFormat(QSettings::IniFormat);
QSettings IniFile;

以上代码将使用 INI 格式,设置存储在 FOLDERID_RoamingAppData

例如:FOLDERID_RoamingAppData\<K_COMPNAME>\<K_INIFILENAME>

现在只有一个构造函数可以像这样存储在本地 INI (settings.ini) 文件中:

QSettings IniFile(K_INIFILENAME,QSettings::IniFormat);