Using resources in Qt

From Qt Wiki
Jump to navigation Jump to search

Template:ArticleMetaData

Overview[edit | edit source]

This snippet shows how to add and reference resources in Qt.

Preconditions[edit | edit source]

None

Using resources in Qt[edit | edit source]

QRE.pro[edit | edit source]

Add a resource file to a project file:

  1. Copyright (c) 2009 Nokia Corporation

TEMPLATE = app TARGET = QRE QT += core \

   gui

SOURCES += main.cpp

  1. This is how the qre.qrc is added to the project.

RESOURCES += qre.qrc

qre.qrc[edit | edit source]

Add resources to a resource file:

<RCC>

   <qresource prefix="/" >
       <file>qt-logo.png</file>
   </qresource>

</RCC>

qt-logo.png[edit | edit source]

File:Qt-logo.png

main.cpp[edit | edit source]

Reference resources from the code:

/*

* Copyright (c) 2009 Nokia Corporation
*/
  1. include <QtGui>
  2. include <QApplication>

int main(int argc, char *argv[]) {

   QApplication a(argc, argv);
   /* QMainWindow as our window */
   QMainWindow* w = new QMainWindow;
   /* QFrame as our centralWidget */
   QFrame* centralW = new QFrame(w);
   w->setCentralWidget(centralW);
   /* QVBoxLayout as our central widgets layout */
   QVBoxLayout* layout = new QVBoxLayout(centralW);
   centralW->setLayout(layout);
   /* QLabel is used as our logo container. */
   QLabel* qtLogoContainer = new QLabel;
   /* QPixmap is used to load the image from resources
    * defined in qre.qrc file. */
   qtLogoContainer->setPixmap(QPixmap(":/qt-logo.png"));
   /* To get the logo shown we need to add the container containing
    * the logo to the layout. */
   layout->addWidget(qtLogoContainer);
   /* We'll display the window maximized. */
   w->showMaximized();
   /* Run till the execution ends. */
   int returnValue = a.exec();
   /* Flag the window to be deleted.*/
   w->deleteLater();
   /* Return the execution return value.*/
   return returnValue;

}

Postconditions[edit | edit source]

Now you know how to add and reference resources in Qt.

File:QRE.png

See also[edit | edit source]