How to get the checked items listed in a Qt QListWidget

John picture John · Mar 24, 2015 · Viewed 7.6k times · Source

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.

Answer

svlasov picture svlasov · Mar 24, 2015

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))