简体   繁体   English

如何获取 Qt QListWidget 中列出的已检查项目

[英]How to get the checked items listed in a Qt QListWidget

I've populated a QListWidget with a list of items and added a check box leaving everything unchecked.我用项目列表填充了一个 QListWidget 并添加了一个复选框,使所有内容都未选中。

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.然后用户单击 QListItem 中的一些项目并单击 gui 上的“生成文件”按钮。

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

I want to get a list of all the checked QListItems.我想获取所有已检查 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.上面的内容获取列表中的 selectedItem。 I've tried get checkState(), getChecked(), but they don't exist for QListWidget items.我试过 get checkState()、getChecked(),但它们对于 QListWidget 项不存在。

Any clues are much appreciated.任何线索都非常感谢。

Thanks,谢谢,

John.约翰。

You need to check if checkState is actually Qt.Checked :您需要检查checkState是否实际上是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())

The above answer is close, missed the .text()<\/strong> .上面的答案很接近,错过了.text()<\/strong> 。 I'm not worthy to comment so the correction is as follows:我不值得评论,所以更正如下:

checked_items.append( self.listWidgetLabels_fields.item(index).text())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM