Load icon from resource
Hello everyone, I meet a problem which is quite weird.
I set up a treeview and add some rows in it. Then I want to add icons for them. It goes well when I add them by
//myicon = new QIcon("C:/Users/yz001/Documents/Qt/Learning Qt/QtToDoListV1_0/inbox.png");
However, when I add the picture into my resource and add them by
myicon = new QIcon(":/inbox.png");
They just don't show up.
Could you please me how to make it via resource?
The following is part of my code:
ui->treeView->setModel(taskModel); //set model ui->treeView->header()->hide(); //hide header ui->treeView->setRootIsDecorated(false); //hide the root //myicon = new QIcon("C:/Users/yz001/Documents/Qt/Learning Qt/QtToDoListV1_0/inbox.png"); myicon = new QIcon(":/icons/inbox.png"); QStandardItem* item_inbox = new QStandardItem(QString("Inbox")); QStandardItem* item_starred = new QStandardItem(QString("Starred")); QStandardItem* item_today = new QStandardItem(QString("Today")); QStandardItem* item_week = new QStandardItem(QString("Week")); item_inbox->setIcon(*myicon);
You must add a qres file to you project
Right click this and add picture to it.
Then you can use
new QIcon(":/inbox.png"); syntax
":/" is syntax for images/files in a res file.
use the first pat on how to add the qres file.
"Finish. Then, the Designer will provide us with resource editor."
Then right click this new file (Myres) and add image to it.
it looks fine.
Right click the actual image and u can get right path directly. (Copy path)
It will be like ":/icons/inbox.png"
The path seems fine. Make sure you re-run qmake (Build->run qmake) after you change your resources.
On another note you've created a memory leak. Don't create QIcons on the heap, there's no point. This is enough:
QStandardItem* item_inbox = new QStandardItem(QIcon(":/icons/inbox.png"), "Inbox");
Thank you. It works after run qmake. But could you please tell me why I need to run qmake after change my resources?In fact, this is my first time to run qmake before build a app. I still don't know the role of the qmake.
qmake is the tool that generates makefiles that your build tool uses to compile the project. It also runs moc, uic, ad rcc tools to generate QObject metadata, transform .ui into .h files and transform the .qrc file into .cpp file (open the build directory to see the generated files). In most cases it runs automatically (like when you add a file to your project or edit a .ui file), but it's spotty in some situations and you need to run it manually. A good rule of thumb is to run it manually whenever you change contents of the .pro file or modify resources. In general a majority of "weird behavior" like program not seeing some changes you made in code/config can be fixed be re-running qmake.
Thank you. This information is really helpful for me:)