Put icon in window Qt5

1

I start to learn Qt and one of the errors that I have not been able to solve is placing an icon in my program's window.

I have the following example:

#include <QApplication>
#include <QWidget>
#include <QIcon>

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

  QApplication app(argc, argv);  

  QWidget window;

  window.resize(250, 150);
  window.setWindowTitle("Icon");
  window.setWindowIcon(QIcon("icono.png"));
  window.show();

  return app.exec();
}

This works as long as the icono.png image is in my / home / user path but I want to get the image of the root folder of the project without having to specify the route when calling the image. E.g.

window.setWindowIcon(QIcon("/toda/la/ruta/del/proyecto/iconos/icono.png"));
    
asked by akko 09.04.2017 в 07:12
source

1 answer

1

For those things, Qt provides the mechanism of resources .

Such a mechanism is a portable way to include external files inside of your application.

It is based on the use of resource files , with extension .qrc , that are added to your project. Resource compiler Qt embeds in your final file, and they can be accessed as a normal file , by QFile , using a special form em> de path : starting with the character : .

The issue is not complex, and the Qt5 documentation about it details it very well, with several examples.

Assuming that your project has the following structure:

  

Project
  + - proyecto.pro
  + - src
  + - builds
  + - images

You should add the following line in your proyecto.pro :

RESOURCES = proyecto.qrc

Now, you create the file proyecto.qrc , with the following content:

<!DOCTYPE RCC><RCC version="1.0">
<qresource>
  <file>images/icono.png</file>
</qresource>
</RCC>

You create the images directory (if you do not already have it), and put the icon there.

Last, a couple of minor changes to your code.

#include <QApplication>
#include <QWidget>
#include <QIcon>

int main( int argc, char *argv[] ) {
  QApplication app( argc, argv );  
  Q_INIT_RESOURCE( graphlib ); // <-- IMPORTANTE

  QWidget window;

  window.resize( 250, 150 );
  window.setWindowTitle( "Icon" );
  window.setWindowIcon( QIcon( ":/images/icono.png" ) );
  //                           ^^^ RUTA ABSOLUTA DESDE LA RAIZ DEL PROYECTO
  window.show( );

  return app.exec( );
}

After these changes (and maybe some minor one, to adapt it to the real names that you use), we'll already make do

  

qmake
make

Your application will have a nice icon: -)

    
answered by 09.04.2017 в 08:40