如何将不可编译的配置文件添加到QT Project中?

How to add non compilable configuration file into QT Project?

我在 QT 项目中有一个 .txt 文件,我在其中存储我的应用程序的设置参数。如果我这样读

void MainWindow::ReadApplicationSettings()
{
   QFile cfgFile("config.txt");
   if(!cfgFile.exists())
   {
      qDebug() << "Cannot find config file.";
   }
   else
   {
      ParseConfigFile(cfgFile);
      SetCfg();
   }
   cfgFile.close();
}

并解析它:

void MainWindow::ParseConfigFile(QFile &cfgFile)
{
    QString line;
    if (cfgFile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
       QTextStream stream(&cfgFile);
       while (!stream.atEnd())
       {
          line = stream.readLine();
          std::istringstream iss(line.toStdString());
          std::string id, eq, val;
          bool error = false;

          if (!(iss >> id))
          {
            error = true;
          }  
          else if (id[0] == '#')
          {
            continue;
          }
          else if (!(iss >> eq >> val >> std::ws) || eq != "=" || iss.get() != EOF)
          {
            error = true;
          }
          if (error) { throw std::runtime_error("Parse error"); }

          cfgMap[id] = std::stoi(val);
     }
   }
}

文件存在,解析开始时文件内容为空

The result of: line = stream.readLine(); is "".

如果我像资源文件一样添加文件并以这种方式打开:

QFile cfgFile(":config.txt");

工作正常,但问题是配置文件已编译,当您必须更改某些值时,必须重建项目才能使用效果

我尝试像那样构建路径 QDir::currentPath + "/config.txt",但效果不佳。

您可以在个人资料中使用 QMAKE_EXTRA_TARGET,例如:

copyfile.commands += $${QMAKE_COPY} $$system_path($$PWD/config.txt) $$system_path($$DESTDIR/)
first.depends = $(first) copyfile
QMAKE_EXTRA_TARGETS += first copyfile

但要确保你的 $$DESTDIR 是正确的。

另一个选项是 Qt 5.6 中未记录的功能 "file_copies",您可以像这样使用它:

CONFIG += file_copies                                                                                                                                                              
configfiles.path = $$OUT_PWD                                                                                                                                                         
configfiles.files = $$PWD/config.txt                                                                                                                                              
COPIES += configfiles

在此处找到: 如果你不喜欢这个方法,那post还有更多的选项可以选择。

顺便说一下,看一下您的 ParseConfigFile() 方法,您的 config.txt 似乎是格式为:key = value 的行的集合,与经典的 INI 文件非常相似。也许你可以像这样使用 QSettings 第三个构造函数:

QSettings settings("config.txt", QSettings::IniFormat);