Qt Resources

Almost any application has a few associated resources, term that in this context is used to identify external files containing non mutable information used by the application.

A typical example of a resource is an icon that is associated to the main window to be displayed on the title bar. So here we'll see how to use a previously created image for this task.

First thing, we put our image in a subfolder of our development directory. Let's say now we have it in ".\images\app.png".

In Qt Creator we create form the menu File a new file, let's say we call it "MyApp.qrc", specifying we want it to be a Qt Resource file, and we want it added to the project.

We open our newly created resource file and we add the app.png file to the contained list of files. We could use a prefix to partition the list in groups, but for the moment this is not a concern for us.

Before we can access the resources listed in the resouce file, we should say in the code that we want to use it. We do that through a macro that we call just at the beginnig of the main function:

int main(int argc, char** argv)
{
Q_INIT_RESOURCE(MyApp);
// ...

Given that, now we can write in the constructor of our main window something like that:

WinMain::WinMain(QWidget *parent) : QMainWindow(parent)
{
setWindowIcon(QIcon(":/images/app.png"));
// ...

We call the QWidget method setWindowIcon() to define the associated icon. It accepts in input a reference to a QIcon, that could be created by passing a file name. If the file name starts with a colon-slash (:/) the QIcon understands we are not passing a real file name, but a resource name.

No comments:

Post a Comment