Search code examples
pythoniconspysideqlistwidgetpyside2

Pyside QWidgetList item assign multiple icons


I know how to assign 1 icon to an item in a QWidgetList. Is it possible to assign more than 1 icon? Like in the image I've attached, I'd like to add a second icon (the green one) to 'a' and be able to remove it on certain conditions. The code below is a just an example of what I'm trying to achieve

enter image description here

from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *

class MainWindow(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        self.orange = QIcon('orangeIconPath')
        self.green = QIcon('greenIconPath')
        self.layout=QVBoxLayout()
        self.setLayout(self.layout)

        self.widget1=QWidget()
        self.layout.addWidget(self.widget1)

        self.layout1=QVBoxLayout()
        self.widget1.setLayout(self.layout1)

        self.layout1.addWidget(QLabel("First layout"))
        self.qlist = QListWidget()
        self.layout1.addWidget(self.qlist)

        items = ['a','b','c']
        self.qlist.addItems(items)

        #This is where I'm struggling when it's more than 1 icon
        #enter a condition to check against each item and assign icon/s to the item when condition is met

        self.show()

Solution

  • No, not with a QListWidget, at least not on its own.

    You have a number of options available to you, though.

    My personal preference in this case is to use QTreeWidget. A QTreeWidget acts very much like a QListWidget with multiple columns, so you can put icons in those columns. You'll need to fiddle with it some to configure the column widths and maybe remove the header bar if you don't want it there, but it isn't particularly difficult (and I'd be happy to provide additional advice if needed). You can also use QTableWidget for the same purpose but it takes more configuration to get it to behave like a list.

    Another option would be to programmatically generate new icons with multiple icons side-by-side so you're only setting a single image.

    Significantly more advanced would be to create a delegate for the view. I won't go into detail on this here because it's a LOT of work, but it also gives you the most control.


    As a side note, I would recommend against using QListWidget / QTreeWidget / QTableWidget view classes. They're really easy to pick up, true, but it really is worth familiarizing yourself with using the model-view QListView / QTreeView / QTableView classes. It's super easy to write a QAbstractListModel or QAbstractTableModel subclass of your own, or you can use QStringListModel for simple lists and QStandardItemModel as a stepping stone between the two types of view classes.