gpt4 book ai didi

c++ - 阅读应用程序设置最佳实践

转载 作者:太空狗 更新时间:2023-10-29 19:43:21 24 4
gpt4 key购买 nike

在我的桌面应用程序中,我使用 QSettings 来保存各种应用程序值。例如,主窗体位置、最近的文档、连接参数和一些改变应用程序行为方式的东西,例如信息对话框中的“不再显示此消息”。

我通常的处理方式是在应用程序启动时将所有设置读入结构或对象,并在应用程序关闭时保存它们。

我还有一个对话框,可以让我编辑设置对象中的许多值,并在对话框关闭时保存它们。

许多窗口和非可视对象都需要设置对象中的值。

执行此操作的最佳方法是什么?

我开始时将设置对象作为主窗口的成员,但后来我遇到了其他窗口需要访问主窗口成员的问题。

我确实认为我可以在它自己的 cpp 文件中创 build 置对象,并在需要的地方#include。但我不确定这是否可能或它的语法。

这种情况的最佳做法是什么?

最佳答案

我建议始终使用 QSettings ,避免补充结构或类。您可以在主程序中设置应用程序名称组织名称组织域

来自 QtDocs:

If you use QSettings from many places in your application, you might want to specify the organization name and the application name using QCoreApplication::setOrganizationName() and QCoreApplication::setApplicationName(), and then use the default QSettings constructor:

QCoreApplication::setOrganizationName("MySoft");
QCoreApplication::setOrganizationDomain("mysoft.com");
QCoreApplication::setApplicationName("Star Runner");

然后在需要访问属性的地方使用默认构造函数:

QSettings settings;

QSettings objects can be created either on the stack or on the heap (i.e. using new). Constructing and destroying a QSettings object is very fast.

您可以在程序的任何位置进行设置:

If there already exists a setting with the same key, the existing value is overwritten by the new value. For efficiency, the changes may not be saved to permanent storage immediately. (You can always call sync() to commit your changes.)

你也可以毫无问题地在不同的线程中使用它:

QSettings is reentrant. This means that you can use distinct QSettings object in different threads simultaneously. This guarantee stands even when the QSettings objects refer to the same files on disk (or to the same entries in the system registry). If a setting is modified through one QSettings object, the change will immediately be visible in any other QSettings objects that operate on the same location and that live in the same process.

QSettings can safely be used from different processes (which can be different instances of your application running at the same time or different applications altogether) to read and write to the same system locations. It uses advisory file locking and a smart merging algorithm to ensure data integrity. Note that sync() imports changes made by other processes (in addition to writing the changes from this QSettings).

关于c++ - 阅读应用程序设置最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31337919/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com