QSettings:sync 什么时候同步?

QSettings:sync When does it sync?

来自Qt帮助功能:

void QSettings::sync() Writes any unsaved changes to permanent storage, and reloads any settings that have been changed in the meantime by another application. This function is called automatically from QSettings's destructor and by the event loop at regular intervals, so you normally don't need to call it yourself.

这里的"meantime"到底是什么意思?这是否总是将我的设置重置为我启动程序时的设置,这意味着我永远无法在使用 sync() 时在其运行时更改我的配置?

您可以假设 QSettings 是作为全局 std::map<QString, QVariant> 实现的,其作用类似于设置的缓存。文档说:

QSettings stores settings. Each setting consists of a QString that specifies the setting's name (the key) and a QVariant that stores the data associated with the key.

出于效率原因,文档说:

For efficiency, the changes may not be saved to permanent storage immediately. (You can always call sync() to commit your changes.)

每次修改设置都会更新缓存值,但不会更新持久文件。 QSettings 的行为取决于平台。

如果您想知道 store/refresh 位于硬盘驱动器中的文件的频率,您需要知道它所在的位置。

您可以使用 QStandardPaths class 和 QStandardPaths::ConfigLocation 标签检索路径:

qDebug() << QStandardPaths::writableLocation(QStandardPaths::ConfigLocation);

要跟踪文件中的修改(执行同步功能的频率),您可以使用此 python script

回答你的问题:?这是否总是将我的设置重置为我启动程序时的设置,这意味着我永远无法在使用 sync() 时在其运行时更改我的配置?

QSettings::sync 合并来自系统文件的修改和缓存中的修改以将其存储在文件中。如果您有多个应用程序修改同一个文件,它们可能会相互覆盖。

在您的情况下,如果您使用 QSettings 来保存您自己的应用程序的数据,它不会将任何内容恢复到原始状态。它会始终将您的修改写入文件并使缓存保持最新。