Home > Enterprise >  How can I add icons for elements in qt listwidget?
How can I add icons for elements in qt listwidget?

Time:01-06

tool ui

as given in the snapshot, I want to add respective color icons for the items in the listwidget, like the blue icon for blue.png, etc. How can I do it?

and after I drag and drop elements from available textures to selected textures, there should be an icon in that widget as well.

if __name__ == "__main__":
    
    ui_obj = TextureSwatcherUI()
    files = []
    for i in os.listdir("Q:/...../tex_source/"):
        files.append(i)
        list_item = QListWidgetItem(i, ui_obj.available_textures)
        list_item.setIcon("Q:/...../tex_source/red.png") 

This is the snippet where I was trying to get all the files and add them to my widget, now I need to add respective icons next to them as well.

CodePudding user response:

I create one Minimal Example to show how you can add Icon to QListWidgetItem

You should create one QListWidgetItem and set one Icon to it and name(text) and etc and then you add it in QListWidget.

you didn't have to add them by using for loop.

import sys
from PySide6.QtWidgets import QApplication,QListWidget,QListWidgetItem
from PySide6.QtGui import QIcon

def main():
    app = QApplication(sys.argv)
    listWidget = QListWidget()

    #Resize width and height
    listWidget.resize(300,120)
    icon1 = QIcon("/home/parisa/ListWidget/check.png");
    listWidget.addItem(QListWidgetItem(icon1,"Item 1"));
    icon2 = QIcon("/home/parisa/ListWidget/crossout.png");
    listWidget.addItem(QListWidgetItem(icon2,"Item 2"));
    listWidget.addItem(QListWidgetItem("Item 3"));
    listWidget.addItem(QListWidgetItem("Item 4"));


    listWidget.setWindowTitle('This is Minimal Example')

    listWidget.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()


The Result:

enter image description here

  • Related