Qt with yaml-cpp in qrc file
-
wrote on 12 Aug 2021, 10:19 last edited by
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?
-
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?
wrote on 12 Aug 2021, 10:26 last edited by@Nan-Feng said in Qt with yaml-cpp in qrc file:
It seems that yaml-cpp cannot recognize the .yaml file in this qrc. Is there any solution?
If you want to got help, you have to show the code you are using to read the yaml file from qrc.
-
wrote on 12 Aug 2021, 10:32 last edited by
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 -
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 normallywrote on 12 Aug 2021, 11:55 last edited by KroMignon 8 Dec 2021, 13:58@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()); }
-
wrote on 12 Aug 2021, 19:48 last edited by
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.)
1/5