Search code examples
pythonpyqt5qlistwidgetqlistwidgetitem

how to check item in QlistWidget and run function on the selected items in python pyqt5


I have a python that display a GUI app that includes qlistwidget that handles items and where the user can select these items by checking them and not select them using

itemSelectionChanged.connect.

I want once the user check the desired items the system save them in order to run another function on the CHECKED items.

like the image below :

enter image description here

here nothing is happen.

Until now i am able to save the checked items when the user select them.like this.

enter image description here

here the result displayed now is:

Checked items:  event_type, number_person

QlistWidget:

   self.header_list = QtWidgets.QListWidget(self)
     self.header_list.setObjectName("listWidget")
     self.header_list.setMaximumWidth(120)
     self.header_list.setSelectionMode(QAbstractItemView.MultiSelection)
     self.header_list.itemSelectionChanged.connect(self.selectionChanged)
     self.horizontallLayout.addWidget(self.header_list)

selectionChanged function :

def selectionChanged(self):
    checked = []
    for row in range(self.header_list.count()):
        item = self.header_list.item(row)
        if item.checkState():
            checked.append(item)
    print("Checked items: ", ", ".join(i.text() for i in checked))
    self.checked = [i.text() for i in checked]

so what is the event listener that can replace itemSelectionChanged in order to save the result on just checking the item and not selecting them.


Solution

  • The check state of item views is stored in the model data, so when the state is changed the data is changed accordingly. QListWidget luckily already provides itemChanged(item):

    This signal is emitted whenever the data of item has changed.

    This obviously means that the signal is emitted whenever any item is changed, and since you're going to check all items anyway you can keep the current function and just connect it to itemChanged instead of itemSelectionChanged.