Pages

Accessing file as resource

It is a common requirement having a file associated to an application, typically containing properties for its setup.

Let's see how adding and using such a resource file to a Qt C++ application when working with Qt Creator.

Qt stores the information for accessing resources in ancillary XML files identified by the qrc extension. Create a new resource file in Qt Creator is just a matter of creating a new file in the current project, of "Qt" type and "Qt Resource file" specification. Once a resource file is created, we see it in the Resources section of the project.

In the XML file the resources are organized in a structure where is kept the prefix, mimicking the file system structure with the application home directory identified by "/", and the actual file name.

I create a text file named "input.txt" in the home directory for my application, and then I create a textFinder.qrc resource file in my application, and I add, under the home prefix "/" the file "input.txt" I just created. If I open the file with a text editor I see it now contains this XML:
<RCC>
<qresource prefix="/">
<file>input.txt</file>
</qresource>
</RCC>

If I check the project file for my application, I'll see that Qt Creator has added a new section for resources:
RESOURCES += \
textFinder.qrc

Here is a function that uses this resource file:
void MainWindow::loadTextFile()
{
QFile fInput(":/input.txt"); // 1.
fInput.open(QIODevice::ReadOnly); // 2.

QTextStream sin(&fInput); // 3.
QString line = sin.readAll(); // 4.
fInput.close(); // 5.

ui->textEdit->setPlainText(line); // 6.
}

1. QFile ctor accepts as input the file name to be accessed. In this case we want to access a resource, to let it know that to QFile, we prefix the name with a colon ':'.
2. A file could be opened in a few different modes. Here we choose to open it only for reading.
3. We create a textual stream referring to our file handler, and we use it to read from it in memory.
4. Since our file is small, it makes sense to read it all and putting its content in a single string. QTextStream provides another function, readLine(), that gets just one line.
5. It is a good idea to explicitly close a file when we are done with it. In any case, the QFile dtor close it implicitly.
6. This is a GUI application, with form created by Qt Creator. Here I am accessing the textEdit component I have previously put in the form associated to this (main) window. This component is of type QTextEdit, we call on it a method, setPlainText(), to reset its content.

This post is based on the article Creating a Qt C++ Application from the official Qt Reference Documentation for Qt Creator 2.1.

No comments:

Post a Comment