Monday 30 December 2013

Use Qt Resource System to package resource files into binary

Why need Qt Resource System? It can help us to package all resource files(image, qml, etc.) into our app's executable. 
To do this, you need to follow below steps:
1. Create qrc file and configure it in pro file
I have resources.qrc file, in my gui.pro file I configure it like so: (see red words)
QT += qml quick
TARGET = gui
!android: !ios: !blackberry: qtHaveModule(widgets): QT += widgets
include(src/src.pri)
RESOURCES += \
    resources.qrc

HEADERS +=

2.  Edit resources.qrc file to contain all resource files in project folder
In my project folder, I have some qml files located under qmls folder and its sub folders, the resources.qrc is in the project folder. Some image files are under images folder. See my folder tree below:
├── gui.pro
├── images
│   ├── header.png
│   └── selectedrow.png
├── qmls
│   ├── a.qml
│   ├── main.qml
│   ├── menu.qml
│   ├── props
│   │   ├── input
│   │   │   └── b.qml
│   │   ├── output
│   │   └── processor
│   ├── README
├── resources.qrc
└── src
    ├── main.cpp
    └── src.pri
Add all these resource files into resources.qrc manually.
<!DOCTYPE RCC>
<RCC version="1.0">
  <qresource prefix="/">
    <file>qmls/main.qml</file>
    <file>qmls/menu.qml</file>
    <file>qmls/a.qml</file>
    <file>qmls/props/input/b.qml</file>
    <file>images/selectedrow.png</file>
    <file>images/header.png</file>
  </qresource>
</RCC>
All above configured resource files will be compiled into app executable.

3. In main.cpp, use URL to load main.qml file
     QQmlApplicationEngine engine(QUrl("qrc:/qmls/main.qml"));
4. In qml files, use relative path to load other resource files, for example:
    Button {
        id: saveMenu
        anchors.left: openMenu.right
        text: "Save"
        iconSource: "../images/selectedrow.png"

That's all. When compiling your app, Qt will create a qrc_resources.cpp file which contain static C++ array to contain the compressed data from resource files. Below is code snippet from my project's qrc_resources.cpp file.
#include <QtCore/qglobal.h>
static const unsigned char qt_resource_data[] = {
  // /home/dean/work/arcgis-3d-scene-builder/source/builder/gui/qmls/main.qml
  0x0,0x0,0x2,0x38,
  0x0,
  0x0,0xa,0x71,0x78,0x9c,0xdd,0x55,0xdf,0x8f,0x9a,0x40,0x10,0x7e,0xe7,0xaf,0x98,
  0xf8,0xd8,0x26,0x4,0xb1,0xb5,0x17,0x12,0xd3,0xf4,0x4c,0xd3,0x36,0x69,0x93,0xb3,
  0x5e,0xda,0xbe,0xae,0xcb,0xa8,0x9b,0x2e,0x2c,0xdd,0x1d,0xe2,0x99,0x8b,0xff,0x7b,
  0x17,0x4,0x14,0x1,0x83,0xda,0x7b,0xe9,0x3e,0x0,0x3b,0xf3,0xed,0xfc,0xf8,0x76,
  0x66,0x10,0x51,0xa2,0x34,0xc1,0x8c,0x66,0xa9,0xe0,0xbf,0xc1,0x77,0x87,0x8e,0xa8,
...

No comments:

Followers

Contributors