PYQT,下拉复选框的实现

下拉复选框的实现

https://blog.csdn.net/LJX4ever/article/details/78039318
写的非常棒,但是他只能进行show操作,把下拉复选框单独变成一个窗口来进行打开,这样的话不能满足实际需求,于是思考了一番对它进行了如下修改。

class ComboCheckBox(QComboBox):
    def __init__(self, parent,items):  # items==[str,str...]
        super(ComboCheckBox, self).__init__(parent)
        self.items = items
        self.items.insert(0, '全部')
        self.row_num = len(self.items)
        self.Selectedrow_num = 0
        self.qCheckBox = []
        self.qLineEdit = QLineEdit()
        self.qLineEdit.setReadOnly(True)
        self.qListWidget = QListWidget()
        self.addQCheckBox(0)
        self.qCheckBox[0].stateChanged.connect(self.All)
        for i in range(1, self.row_num):
            self.addQCheckBox(i)
            self.qCheckBox[i].stateChanged.connect(self.show)
        self.setModel(self.qListWidget.model())
        self.setView(self.qListWidget)
        self.setLineEdit(self.qLineEdit)

    def addQCheckBox(self, i):
        self.qCheckBox.append(QCheckBox())
        qItem = QListWidgetItem(self.qListWidget)
        self.qCheckBox[i].setText(self.items[i])
        self.qListWidget.setItemWidget(qItem, self.qCheckBox[i])

    def Selectlist(self):
        Outputlist = []
        for i in range(1, self.row_num):
            if self.qCheckBox[i].isChecked() == True:
                Outputlist.append(self.qCheckBox[i].text())
        self.Selectedrow_num = len(Outputlist)
        return Outputlist

    def show(self):
        show = ''
        Outputlist = self.Selectlist()
        self.qLineEdit.setReadOnly(False)
        self.qLineEdit.clear()
        for i in Outputlist:
            show += i + ';'
        if self.Selectedrow_num == 0:
            self.qCheckBox[0].setCheckState(0)
        elif self.Selectedrow_num == self.row_num - 1:
            self.qCheckBox[0].setCheckState(2)
        else:
            self.qCheckBox[0].setCheckState(1)
        self.qLineEdit.setText(show)
        self.qLineEdit.setReadOnly(True)

    def All(self, zhuangtai):
        if zhuangtai == 2:
            for i in range(1, self.row_num):
                self.qCheckBox[i].setChecked(True)
        elif zhuangtai == 1:
            if self.Selectedrow_num == 0:
                self.qCheckBox[0].setCheckState(2)
        elif zhuangtai == 0:
            self.clear()

    def clear(self):
        for i in range(self.row_num):
            self.qCheckBox[i].setChecked(False)

原文章当中不能在窗口内显示的原因就是没有继承,在__init__的时候进行parent继承操作。
在实例化的时候只需要实例化一个Qwidgt以及一个ComboCheckBox即可,代码如下:

self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.comboBox = ComboCheckBox(self.centralwidget,provinces)
self.comboBox.setGeometry(QtCore.QRect(810, 100, 191, 51))
self.comboBox.setObjectName("comboBox")

再将窗口实例化,效果如下图所示
PYQT,下拉复选框的实现_第1张图片

你可能感兴趣的:(PYQT,下拉复选框的实现)