c++ - Qt 控制台应用程序的标准配置方法是什么?

标签 c++ linux qt qtcore qsettings

在 .Net 中,您通常有一个 app.config 文件和内置的访问配置的方法。

是否有使用 Qt 进行配置的等效标准方法?

例如,假设我的应用程序连接到在线服务器,我希望能够存储连接详细信息(用户定义)。

这是“自己动手”的情况,还是有一种方法可以使用 XML 或 Qt 提供的具有简单读/写方法的任何其他格式来存储和读取这些配置?

编辑:为问题添加一些复杂性。这是一个 Linux 控制台应用程序,因此请专门寻找基于文件和透明的配置。

最佳答案

您可以为此使用QSettings。详情请引用文档:

http://qt-project.org/doc/qt-5.1/qtcore/qsettings.html

您始终可以使用其他格式,如 XML、Json 等,但一般来说,QSettings 是一种方式,或者如果您正在编写 KDE 应用程序,则可能 KConfig

这是您在处理 QSettings 读写时需要注意的两个重要方法:

Reading

QVariant QSettings::value(const QString & key,
                          const QVariant & defaultValue = QVariant()) const

Writing

void QSettings::setValue(const QString & key, const QVariant & value)

然后,您可以简单地坚持使用 native 格式(如果您愿意,甚至可以使用 Linux 上的 ini):

QSettings::NativeFormat 0 Store the settings using the most appropriate storage format for the platform. On Windows, this means the system registry; on Mac OS X, this means the CFPreferences API; on Unix, this means textual configuration files in INI format.

为方便起见,您可以在此处找到示例:

#include <QSettings>

int main()
{
    ....

    QSettings settings("Foo", "Bar");

    // settings.beginGroup("application");
    QString string = settings.value("foo", "bar");
    // settings.endGroup();

   ....

}

请注意,这些组是可选的,这取决于您的具体目的。您可以通过这种方式对设置进行分组,以将某些设置封装起来。

根据文档,这对您来说可能也很重要:

On Unix systems, if the file format is NativeFormat, the following files are used by default:

  • $HOME/.config/MySoft/Star Runner.conf (Qt for Embedded Linux: $HOME/Settings/MySoft/Star Runner.conf)

  • $HOME/.config/MySoft.conf (Qt for Embedded Linux: $HOME/Settings/MySoft.conf)

  • /etc/xdg/MySoft/Star Runner.conf

  • /etc/xdg/MySoft.conf

关于c++ - Qt 控制台应用程序的标准配置方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19195182/

相关文章:

C++错误消息ostream未命名类型

c++ - 尝试 std::lock[_unique] std::shared_mutex 的线程是否会被调用 std::lock_shared 的线程饿死?

c++ - 从 C++ 函数返回批量数据的最佳数据类型

c - 如何获得符号链接(symbolic link)的绝对路径?

linux - 施根 : pass a command to be executed as if it’s in a shell

linux - 使用 Expect 填写多行提示

c++ - 从 C++ 向 QML 发出信号以读取 Q_PROPERTY 是一个同步事件吗?

qt - QNetworkRequest::User 和 QNetworkRequest::UserMax 的区别

c++ - 使用 C++20 概念实现 Pair 概念

c++ - 是否有用于检测 USB 事件(插入和移除)的 Qt 解决方案?