How to add app icon in Qt?

If you do not set an icon for your qt project, the built exe has a default icon, which seems a blank window. If you run the program, the icon of its window is also the blank window icon. How to change the default app icon?

If you only want to change the icon of the executable, you can prepare an icon image such as myprogrammingnotes.com.ico, and a .rc file myprogrammingnotes.com.rc which contains the following line:

1 ICON “myprogrammingnotes.com.ico”

The first field is the resource id which can be any value you want. The second field is the resource type, which is ICON for specifying the icon file. The third field is the actual icon image file name. Now add the following line to the .pro file of your project:

RC_FILE = myprogrammingnotes.com.rc

, build your program, and you will find the generated .exe file shows the icon in explorer. There can be multiple icon resources in a .rc file. The displayed exe icon is the icon with the least resource id.

Unfortunately, the icon of the window of your program is still not changed. I used to using the following code to set window icon but it seems not working in 64 bit environment:

hInstance=(HINSTANCE)GetModuleHandle(NULL);
SetClassLong((HWND)winId(),GCLP_HICON,(long)LoadIcon(hInstance,MAKEINTRESOURCE(1)));

The program cannot compile complaining

error: cast from 'HICON {aka HICON__*}' to 'long int' loses precision [-fpermissive]
     SetClassLong((HWND)winId(),GCLP_HICON,(long)LoadIcon(hInstance,MAKEINTRESOURCE(1)));
                                                                                      ^

Even I use the following code to make the compiler happy, I still cannot change the window icon:

SetClassLong((HWND)winId(),GCLP_HICON,(long long)LoadIcon(hInstance,MAKEINTRESOURCE(1)));

In fact, it is not necessarily to use a .rc file to modify the icon. You can add icon to project directly:

RC_ICONS += myprogrammingnotes.com.ico

RC_ICONS will guide qmake to generate a .rc file automatically and write the icon resource to it. After qmaking and rebuilding, you will find both the icon of the .exe and the icon of the window of your program are changed. You do not need to call the setClassLong function to set the window’s icon.

Note that you cannot use RC_ICONS  file and RC_FILE in .pro file at the same time, otherwise, the .rc file will override the RC_ICONS.

 

 

 

If you like my content, please consider buying me a coffee. Buy me a coffeeBuy me a coffee Thank you for your support!
Posted in

Leave a Reply