我们将 .pro 文件设置为资源,然后在运行时将其读回并显示到控制台中。

正如我们在图片中看到的,我们(application.exe)可以在运行时访问资源。
Qt 资源系统是一种独立于平台的机制,用于在应用程序的可执行文件中存储二进制文件。如果我们的应用程序总是需要一组特定的文件(图标、翻译文件等)并且我们不想冒丢失文件的风险,这很有用。
资源系统基于 qmake、rcc(Qt 的资源编译器)和QFile之间的紧密合作。
与应用程序关联的资源在 .qrc 文件中指定,这是一种基于 XML 的文件格式,列出磁盘上的文件,并可选择为它们分配资源名称,应用程序必须使用该资源名称来访问资源。
这是一个示例 .qrc 文件:
<!DOCTYPE RCC><RCC version="1.0">
<qresource>
<file>images/copy.png</file>
<file>images/cut.png</file>
<file>images/new.png</file>
<file>images/open.png</file>
<file>images/paste.png</file>
<file>images/save.png</file>
</qresource>
</RCC>
让我们制作我们的资源文件。
右键单击项目->添加新…

选择…

点击下一步

结束。然后,Designer 会为我们提供资源编辑器。

让我们制作我们的资源文件。
添加->添加前缀

我们可以更改名称但保留正斜杠(’/’)。然后,添加-> 添加文件。

我们将使用我们的.pro文件作为资源。
我们可以更改名称但保留正斜杠(’/’)。然后,添加-> 添加文件。

我们可以通过右键单击文件将资源的路径放入剪贴板。然后,我们可以从剪贴板中检索它。

在下面的代码中,我们将 .pro 文件设置为资源。在运行时,我们会将其读回并显示到控制台中。这是代码:
#include <QCoreApplication>
#include <QFile>
#include <QString>
#include <QDebug>
#include <QTextStream>
void read(QString filename)
{
QFile file(filename);
if(!file.open(QFile::ReadOnly |
QFile::Text))
{
qDebug() << " Could not open the file for reading";
return;
}
QTextStream in(&file);
QString myText = in.readAll();
// put QString into qDebug stream
qDebug() << myText;
file.close();
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
read(":/MyPreciousRes/MyResources.pro");
return a.exec();
}
运行,我们得到的输出是我们的 .pro 文件:
"#-------------------------------------------------
#
# Project created by QtCreator 2013-09-13T11:02:43
#
#-------------------------------------------------
QT += core
QT -= gui
TARGET = MyResources
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
SOURCES += main.cpp
RESOURCES += \
MyRes.qrc
"
注意突出显示的行。我们的.pro为资源添加了行!