How to get the checked items listed in a Qt QListWidget

大兔子大兔子 提交于 2019-12-12 07:27:59

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/29238394/how-to-get-the-checked-items-listed-in-a-qt-qlistwidget

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!