pyqt5 下拉复选框的实现

PyQt5 创建下拉复选框

总体目录结构

要先自定义下拉复选框类

参考:自定义实现 PyQt5 下拉复选框 ComboCheckBox

# 下拉复选框测试/combocheckbox.py
from PyQt5.QtWidgets import QComboBox, QLineEdit, QListWidget, QCheckBox, QListWidgetItem


class ComboCheckBox(QComboBox):
    def __init__(self,parent):
        """
        initial function
        """
        super(ComboCheckBox, self).__init__(parent)

        self.box_list = []  # selected items
        self.text = QLineEdit()  # use to selected items
        self.state = 0  # use to record state
        # self.setStyleSheet("width: 300px; height: 50px; font-size: 21px; font-weight: bold")
        self.text.setReadOnly(True)
        self.setLineEdit(self.text)


    def myadditems(self,items ):
        """

        :param items: 传入下拉选项
        :return:
        """
        self.items = ["全选"] + items  # items list
        q = QListWidget()
        for i in range(len(self.items)):
            self.box_list.append(QCheckBox())
            self.box_list[i].setText(self.items[i])
            item = QListWidgetItem(q)
            q.setItemWidget(item, self.box_list[i])
            if i == 0:
                self.box_list[i].stateChanged.connect(self.all_selected)
            else:
                self.box_list[i].stateChanged.connect(self.show_selected)

        # q.setStyleSheet("font-size: 20px; font-weight: bold; height: 40px; margin-left: 5px")
        self.setModel(q.model())
        self.setView(q)

    def all_selected(self):
        """
        decide whether to check all
        :return:
        """
        # change state
        if self.state == 0:
            self.state = 1
            for i in range(1, len(self.items)):
                self.box_list[i].setChecked(True)
        else:
            self.state = 0
            for i in range(1, len(self.items)):
                self.box_list[i].setChecked(False)
        self.show_selected()

    def get_selected(self) -> list:
        """
        get selected items
        :return:
        """
        ret = []
        for i in range(1, len(self.items)):
            if self.box_list[i].isChecked():
                ret.append(self.box_list[i].text())
        return ret

    def show_selected(self):
        """
        show selected items
        :return:
        """
        self.text.clear()
        ret = '; '.join(self.get_selected())
        self.text.setText(ret)

然后进行UI设计

# 下拉复选框测试/下拉复选框test.py
from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(400, 300)
        self.comboBox = ComboCheckBox(Form)
        self.comboBox.setGeometry(QtCore.QRect(70, 60, 281, 21))
        self.comboBox.setObjectName("comboBox")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
from combocheckbox import ComboCheckBox

最后程序内容

import sys
from PyQt5.QtWidgets import QWidget, QApplication
from 下拉复选框test import Ui_Form


class QmyWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)  # 调用父类构造函数,创建QWidget窗体
        self.__ui = Ui_Form()
        self.__ui.setupUi(self)  # self 是Widget窗体,可以作为参数传递给setupUi
        self.__ui.comboBox.myadditems(['a','b','c','d','e'])

if __name__ == '__main__':
    app = QApplication(sys.argv)
    myWidget = QmyWidget()
    myWidget.show()
    sys.exit(app.exec_())

运行效果

posted @ 2023-02-16 14:11  meizhengchao  阅读(757)  评论(0编辑  收藏  举报