Loading image from resources in Qt
QLabel is typically used for displaying text, but it can also display an image. For loading an image from resources, first we need to create a resource file which will have image location. If you already have one resource file then directly jump to step 5.
Making resource file
1. Inside Qt Creator, right click on project name and choose "Add New".
2. Click on "Qt" inside left pane and select "Qt Resource file" inside right pane.
3. Click on "Choose" button, give it a name, click next and Finish
4. New file should be created with .qrc extension
5. If .qrc file is not open then open it by double clicking on it
6. Click on "Add" button and select "Add prefix"
7. Newly generated prefix will be something like "/new/prefix1", lets keep it simple. So I am changing it to only slash / This is used at time of loading file so make sure it is right
Adding image file to resources
8. Now again click on "Add" and now choose "Add Files"
9. Select any jpg file, I did not checked with PNG images but that should also work :) Make sure jpg size and dimensions are not too big. If your file is located outside the project directory then it will ask for making a copy of that image inside project directory. Lets consider the image is in same directory where .qrc file is. You can also make an images folder.
10. If all is done without any mistake then you will see a small image in resource editor
Loading image from resources
11. Put one label on form or your view class, lets say it is myImage. Add the below code at right place
// If you have not initialised it before
myImage = new QLabel();
// If your image is inside "images" folder then try ":/images/imgfromresource.jpg".
// error loading image, show an error message here
- For more information on loading images see http://doc.trolltech.com/4.6/widgets-imageviewer.html