Qt with yaml-cpp in qrc file
-
Hi, I am trying to use Qt and yaml-cpp library to read and write .yaml, if it is an absolute path (C:/test.yaml), everything is normal. If it is a .yaml file in qrc, the program crashes directly and cannot be started. It seems that yaml-cpp cannot recognize the .yaml file in this qrc. Is there any solution?
-
-
code:
YAML::Node config = YAML::LoadFile(":/assets/test.yaml");
std::string value = config["name"].asstd::string();
YAML::Node config = YAML::LoadFile("C:/test.yaml");
std::string value = config["name"].asstd::string();
With the above wording, the program crashes directly.
In the following way of writing, the value corresponding to the name key can be read normally -
@Nan-Feng said in Qt with yaml-cpp in qrc file:
YAML::Node config = YAML::LoadFile(":/assets/test.yaml");
I don't think YAML supports RC files.
You have to read the the yaml file into a QString and then passe it to YAML.Something like:
QFile file(":/assets/test.yaml"); if(file.open(QFile::ReadOnly | QFile::Text)) { QTextStream in(&file); QString myText = in.readAll(); YAML::Node config(myText.toStdString()); }
-
I agree with @KroMignon 's approach.
Another alternative (in case it becomes appealing for any other reason) is to use
QTemporaryFile
:// note the ":" at the front of the path std::string path_inside_qrc = ":/data/sim_rpc_replies_immediate_scores.pbtxt"; std::unique_ptr<QTemporaryFile> temporary_file; temporary_file.reset( QTemporaryFile::createNativeFile(QString::fromStdString(path_inside_qrc)) ); std::string file_name = temporary_file->fileName().toUtf8().constData(); // TODO: add code to use the temporary file. // Delete the temp file after using it temporary_file.reset();
(This is "self plagiarism" from this prior discussion thread.)