Important: Please read the Qt Code of Conduct -

Using icons with QTreeWidgetItem

  • I have an application using a QTreeWidget with tree nodes (QTreeWidgetItem). I would like to add icons to the nodes in my tree. I can get this to work using a file:
    item->setIcon(0, *(new QIcon("test1.gif")));

    I have a resource file where I have added all the images I want to use for icons. How can I set the icon by referencing the resource file rather than directly referencing the image files?

    Thanks for any guidance.

  • Try to replace "test1.gif" with ":/icons/test1.gif".

    Look at the your resource file, the suggested path above must
    look like "<file>icons/test1.gif</file>" inside your resource file.

  • For some reason I can't get this to work.

    My resource file contains:

    To be more complete, here is a larger section of the resource file:
    <qresource prefix="/cirsqr">
    <file>Resources/cirsqr/cir gray - sq gray.gif</file>
    <file>Resources/cirsqr/cir gray - sq green.gif</file>
    <file>Resources/cirsqr/cir gray - sq red.gif</file>
    <file>Resources/cirsqr/cir gray - sq yellow.gif</file>
    <file>Resources/cirsqr/cir green - sq gray.gif</file>
    <file>Resources/cirsqr/cir green - sq green.gif</file>
    <file>Resources/cirsqr/cir green - sq red.gif</file>
    <file>Resources/cirsqr/cir green - sq yellow.gif</file>
    <file>Resources/cirsqr/cir red - sq gray.gif</file>
    <file>Resources/cirsqr/cir red - sq green.gif</file>
    <file>Resources/cirsqr/cir red - sq red.gif</file>
    <file>Resources/cirsqr/cir red - sq yellow.gif</file>
    <file>Resources/cirsqr/cir yellow - sq gray.gif</file>
    <file>Resources/cirsqr/cir yellow - sq green.gif</file>
    <file>Resources/cirsqr/cir yellow - sq red.gif</file>
    <file>Resources/cirsqr/cir yellow - sq yellow.gif</file>

    My code tries to reference this as follows:
    item->setIcon(0, *(new QIcon(":/Resources/cirsqr/test1.gif")));

    The icon is not displayed, which indicates it is not finding the test1.gif image. Do you see anything that I am doing wrong here?

    Thanks again.

  • @
    <qresource prefix="/Resources/cirsqr">

    On my dialog:

    Dialog::Dialog(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog)

    Here is a screenshot:

  • OK, I think I've got it now, I was misunderstanding how the "prefix" was used. My original resource file can work if I reference it like this:
    item->setIcon(0, *(new QIcon(":cirsqr/Resources/cirsqr/test1.gif")));

    Thanks for the help!

  • You're creating a memory leak. QIcon can be used as a value class, you should not create the icons with new.

Log in to reply