如何在python中使用Pyqt5获取列表中选中的QlistWidgetItem总数?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (112)

我有一个将项目添加到QlistWidget的函数。

想添加一个复选框到添加的项目中,用户选中复选框后我需要打印检查项目的总数。

检查checkbox后,什么都不打印。

code:

def ListFilesInViewer(self,Files):              
        for item1 in Files:
            item = QtWidgets.QListWidgetItem(item1)
            item.setCheckState(QtCore.Qt.Unchecked)

            for index in range(self.listWidgetPDFlist.count()):
                if self.listWidgetPDFlist.item(index).checkState() == QtCore.Qt.Checked:
                     print("checked item ==>{}".format(self.listWidgetPDFlist.item(index)))


            self.listWidgetPDFlist.addItem(item)
            self.lineEditTotalPDFnumber.setText(str(self.listWidgetPDFlist.count())) 
提问于
用户回答回答于

尝试一下:

import sys
from PyQt5 import QtWidgets, QtGui, QtCore

class Window(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        self.lineEditTotalPDFnumber = QtWidgets.QLineEdit('QLineEdit')
        self.lineEditTotalPDFnumber.setReadOnly(True)

        self.listWidgetPDFlist = QtWidgets.QListWidget()

        self.vlayout = QtWidgets.QVBoxLayout()
        self.vlayout.addWidget(self.listWidgetPDFlist)
        self.vlayout.addWidget(self.lineEditTotalPDFnumber)

        self.btnAddItems = QtWidgets.QPushButton()
        self.btnAddItems.setText('add items')
        self.vlayout.addWidget(self.btnAddItems)
        self.btnAddItems.clicked.connect(self.addItems)

        self.btnPrintItems = QtWidgets.QPushButton()
        self.btnPrintItems.setText('print the total number of checked items')
        self.vlayout.addWidget(self.btnPrintItems)
        self.btnPrintItems.clicked.connect(self.printItems)

        self.setLayout(self.vlayout)

    def addItems(self):
        Files = ["file1", "file2", "file3",]
        print("\nFiles ", Files)

        self.ListFilesInViewer(Files)

    def ListFilesInViewer(self, Files):              
        for item1 in Files:
            item = QtWidgets.QListWidgetItem(item1)
            print("\titem =",item)
            item.setCheckState(QtCore.Qt.Unchecked)  #Unchecked
            item.setText('`{}` - QListWidget item № `{}`'.format(str(item1), str(self.listWidgetPDFlist.count()))) 
            self.listWidgetPDFlist.addItem(item)  # listWidgetPDFlist

    def printItems(self):
        checkedItem = 0
        for index in range(self.listWidgetPDFlist.count()):
            if self.listWidgetPDFlist.item(index).checkState() == QtCore.Qt.Checked:
                 print("checked item ==>{}, index={}".format(self.listWidgetPDFlist.item(index), index))
                 checkedItem += 1        
        self.lineEditTotalPDFnumber.setText("checked items --> {}".format(str(checkedItem)))


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    window = Window()
    window.resize(500, 400)
    window.show()
    sys.exit(app.exec_())

扫码关注云+社区

领取腾讯云代金券