Getting qrc file paths in Qt

I want to know how to access files in a qrc file to use them as strings in an array. Example qrc file:

   <!DOCTYPE RCC><RCC version="1.0">
    <qresource prefix="">
     <file>images/1.jpg</file>
     <file>images/2.jpg</file>
     <file>images/3.jpg</file>
     <file>images/4.jpg</file>
    </qresource>
   </RCC>

I want to use it as follows:

   for(int i=0;i<4;i++)
   {
     path=image_path[i];
   }

where the path is a qlist, which can subsequently be used to access the corresponding images.

+4
source share
1 answer

This seems like an easy way to do this with QDirIterator .

It may break if there is a directory in the current working directory with the name ":" and you expect it to be analyzed in the future. In any case, this should not be a problem now.

QStringList imageFileList;
QDirIterator dirIterator(":", QDirIterator::Subdirectories);
while (dirIterator.hasNext()) {
    QFileInfo fileInfo = it.fileInfo();
    if (fileInfo.isFile()) // Do not add directories to the list
        imageFileList.append(it.next());
}

, , . , .

main.qrc

<!DOCTYPE RCC><RCC version="1.0">
 <qresource prefix="">
  <file>images/1.jpg</file>
  <file>images/2.jpg</file>
  <file>images/3.jpg</file>
  <file>images/4.jpg</file>
 </qresource>
</RCC>

main.cpp

#include <QXmlStreamReader>
#include <QString>
#include <QFile>
#include <QTextStream>

int main()
{
    QTextStream standardOutput(stdout);
    QFile file("main.qrc");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        standardOutput << "File open error:" << file.errorString() << "\n";
        return 1;
    }
    QXmlStreamReader inputStream(&file);
    while (!inputStream.atEnd() && !inputStream.hasError()) {
        inputStream.readNext();
        if (inputStream.isStartElement()) {
            QString name = inputStream.name().toString();
            if (name == "file")
                standardOutput << "file: :/" << inputStream.readElementText() << "\n";
        }
    }
    return 0;
}

main.pro

TEMPLATE = app
TARGET = main
QT = core
SOURCES += main.cpp

qmake && make && ./main

file: :/images/1.jpg
file: :/images/2.jpg
file: :/images/3.jpg
file: :/images/4.jpg
0

Source: https://habr.com/ru/post/1541868/


All Articles