【问题标题】:Qt/C++ Write/Read Key-Value Pair FileQt/C++ 写/读键值对文件
【发布时间】:2015-08-14 12:06:22
【问题描述】:

我有一个基于 Qt/C++ 小部件的 Mac 应用程序。我有一系列用于存储设置的复选框、单选按钮和文本字段。我想在单击更新按钮时将它们保存到键值对文件中,然后在应用程序加载时读取此文件以将这些小部件设置回正确的状态。

有没有例子说明这是如何在某处完成的?

【问题讨论】:

  • 您可以查看the detailed description of the QFile class,其中有很多关于打开、写入和读取文件的示例。
  • 嗯...看来我可能需要使用QSettings API 作为最佳选择。
  • 对于设置,这可能是更好的选择。但请记住它们的存储方式(基于用户帐户、系统范围等)

标签: c++ qt file-io


【解决方案1】:

以下是我在 Mac 上使用的。但是,如果您修改了settings 对象的setPath(),则可以通过the documentation 使其在其他平台上工作。

mainwindow.h 中,我必须添加这些条目:

void readSettings();
void writeSettings();

在私人插槽下。

然后,在mainwindow.cpp 中,我添加了这些示例函数:

void MainWindow::readSettings()
{
    QSettings settings;
    settings.setPath(settings.IniFormat,settings.SystemScope,"/etc/xdg");
    settings.beginGroup("General");
    ui->checkBox1->setChecked(settings.value("checkBox1",false).toBool());
    settings.endGroup();
}

void MainWindow::writeSettings()
{
    QSettings settings;
    settings.setPath(settings.IniFormat,settings.SystemScope,"/etc/xdg");
    settings.beginGroup("General");
    settings.setValue("checkBox1",ui->checkBox1->isChecked());
    settings.endGroup();
}

您应该阅读QSettings page 上的“范围”和setPath() 以了解更多信息。

然后,在MainWindow::MainWindow() 函数中,我是这样的:

QCoreApplication::setOrganizationName("Example Company");
QCoreApplication::setOrganizationDomain("example.com");
QCoreApplication::setApplicationName("Example Product");

ui->setupUi(this);
this->readSettings();

请注意,您只能在设置 ui 变量后才能使用 readSettings()。通过像我一样使用QCoreApplication 类,我不必一直重新声明我一直在使用的设置。

然后,我取了MainWindow并在上面添加了checkBox1updateButton,并将updateButtonclicked()插槽代码设置为:

this->writeSettings();

现在,当窗口加载时,在绘制 UI 后,它会读取设置以将复选框值设置为单击更新按钮时设置的值。

【讨论】:

  • 在您的readSettings() 中,我会先执行settings.contains(...) 以查看是否设置了值或使用settings.value() 函数的defaultValue 参数。否则,如果由于某种原因缺少设置值,您将不知道小部件中放入了什么。
  • @Bowdzone 我会在几个小时内更新它(上床睡觉)。然而,我遇到了另一个奇怪的情况。文档说 Mac 上的系统范围存储在目录“/etc/xdg”中,但我在我的 Mac 上找不到这个目录。我认为文档不能解释优胜美地(OSX 10.10)上发生的事情。您知道系统范围设置现在存储在哪里吗?
  • 我这辈子从未有过 Mac,对此我一无所知。
  • 我现在已经实现了value() 类方法的defaultValue 部分。
  • 我还在 /etc/xdg 问题上发布了query
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-22
  • 1970-01-01
  • 1970-01-01
  • 2012-09-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多