How to get the checked items listed in a Qt QListWidget
Asked Answered
H

1

6

I've populated a QListWidget with a list of items and added a check box leaving everything unchecked.

for td in root.iter('testdata'):
    test_data = td.get('ins')
    item = QtGui.QListWidgetItem(test_data, self.listWidgetLabels)
    item.setFlags(item.flags() | QtCore.Qt.ItemIsUserCheckable)
    item.setCheckState(QtCore.Qt.Unchecked)

The user then clicks a few of the items in the QListItem and clicks a 'Generate File' button on the gui.

self.pushButtonGenerateFile.clicked.connect(self.generate_file)

I want to get a list of all the checked QListItems.

def generate_driver(self):
    test = self.listWidgetLabels.selectedItems()
    items = []
    checked_items = []
    for index in range(self.listWidgetLabels.count()):
        items.append(self.listWidgetLabels.item(index))

        for x in self.listWidgetLabels.selectedItems():
            checked.append(x.text())
    for i in checked:
        print("Checked Items: {0}".format(i))

What is above gets the selectedItem in the list. I've tried get checkState(), getChecked(), but they don't exist for QListWidget items.

Any clues are much appreciated.

Thanks,

John.

Hysterogenic answered 24/3, 2015 at 16:48 Comment(0)
H
13

You need to check if checkState is actually Qt.Checked:

for index in range(self.listWidgetLabels.count()):
    if self.listWidgetLabels.item(index).checkState() == Qt.Checked:
        checked_items.append(self.listWidgetLabels.item(index).text())
Homey answered 24/3, 2015 at 18:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.