PyQt5 QComboBox中添加带CheckBox的选项

2024-02-03 04:40

本文主要是介绍PyQt5 QComboBox中添加带CheckBox的选项,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

效果

请添加图片描述

代码
"""
可多选的下拉框
通过CheckableComboBox.texts_list 可以获取选中的item值组成的列表;用CheckableComboBox.currentText没法显示全texts_list = []  # 所有选中的item文本组成的列表
item_list = []  # 所有选中的item组成的列表
"""from PyQt5.QtCore import Qt, QEvent
from PyQt5.QtGui import QStandardItem, QFontMetrics, QPalette
from PyQt5.QtWidgets import QStyledItemDelegate, QComboBox, qAppclass CheckableComboBox(QComboBox):# Subclass Delegate to increase item heightclass Delegate(QStyledItemDelegate):def sizeHint(self, option, index):size = super().sizeHint(option, index)size.setHeight(20)return sizedef __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)self.texts_list = []  # 所有选中的item文本组成的列表self.item_list = []  # 所有选中的item组成的列表# Make the combo editable to set a custom text, but readonlyself.setEditable(True)self.lineEdit().setReadOnly(True)# Make the lineedit the same color as QPushButtonpalette = qApp.palette()palette.setBrush(QPalette.Base, palette.button())self.lineEdit().setPalette(palette)# Use custom delegateself.setItemDelegate(CheckableComboBox.Delegate())# Update the text when an item is toggledself.model().dataChanged.connect(self.updateText)# Hide and show popup when clicking the line editself.lineEdit().installEventFilter(self)self.closeOnLineEditClick = False# Prevent popup from closing when clicking on an itemself.view().viewport().installEventFilter(self)def resizeEvent(self, event):# Recompute text to elide as neededself.updateText()super().resizeEvent(event)def eventFilter(self, object, event):if object == self.lineEdit():if event.type() == QEvent.MouseButtonRelease:if self.closeOnLineEditClick:self.hidePopup()else:self.showPopup()return Truereturn Falseif object == self.view().viewport():if event.type() == QEvent.MouseButtonRelease:index = self.view().indexAt(event.pos())item = self.model().item(index.row())if item.checkState() == Qt.Checked:item.setCheckState(Qt.Unchecked)else:item.setCheckState(Qt.Checked)return Truereturn Falsedef showPopup(self):super().showPopup()# When the popup is displayed, a click on the lineedit should close itself.closeOnLineEditClick = Truedef hidePopup(self):super().hidePopup()# Used to prevent immediate reopening when clicking on the lineEditself.startTimer(100)# Refresh the display text when closingself.updateText()def timerEvent(self, event):# After timeout, kill timer, and reenable click on line editself.killTimer(event.timerId())self.closeOnLineEditClick = Falsedef updateText(self):self.texts_list = []self.item_list = []for i in range(self.model().rowCount()):if self.model().item(i).checkState() == Qt.Checked:self.texts_list.append(self.model().item(i).text())self.item_list.append(self.model().item(i))text = ", ".join(self.texts_list)# Compute elided text (with "...")metrics = QFontMetrics(self.lineEdit().font())elidedText = metrics.elidedText(text, Qt.ElideRight, self.lineEdit().width())self.lineEdit().setText(elidedText)def addItem(self, text, data=None):item = QStandardItem()item.setText(text)if data is None:item.setData(text)else:item.setData(data)item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)item.setData(Qt.Unchecked, Qt.CheckStateRole)self.model().appendRow(item)# self.model().item(0).setCheckState(Qt.Checked)  # 将第一个item设置为选中状态def addItems(self, texts, datalist=None):for i, text in enumerate(texts):try:data = datalist[i]except (TypeError, IndexError):data = Noneself.addItem(text, data)def currentData(self):# Return the list of selected items datares = []for i in range(self.model().rowCount()):if self.model().item(i).checkState() == Qt.Checked:res.append(self.model().item(i).data())return resif __name__ == '__main__':from PyQt5 import QtWidgets,QtCoreimport syscomunes = ['Ameglia', 'Arcola', 'Bagnone', 'Bolano', 'Carrara', 'Casola', 'Castelnuovo Magra','Comano, località Crespiano', 'Fivizzano', 'Fivizzano località Pieve S. Paolo','Fivizzano località Pieve di Viano', 'Fivizzano località Soliera', 'Fosdinovo', 'Genova','La Spezia', 'Levanto', 'Licciana Nardi', 'Lucca', 'Lusuolo', 'Massa', 'Minucciano','Montignoso', 'Ortonovo', 'Piazza al sercho', 'Pietrasanta', 'Pignine', 'Pisa','Podenzana', 'Pontremoli', 'Portovenere', 'Santo Stefano di Magra', 'Sarzana','Serravezza', 'Sesta Godano', 'Varese Ligure', 'Vezzano Ligure', 'Zignago']app = QtWidgets.QApplication(sys.argv)Form = QtWidgets.QWidget()comboBox1 = CheckableComboBox(Form)comboBox1.addItems(comunes)Form.show()sys.exit(app.exec_())

这篇关于PyQt5 QComboBox中添加带CheckBox的选项的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/673015

相关文章

PyQt5 GUI 开发的基础知识

《PyQt5GUI开发的基础知识》Qt是一个跨平台的C++图形用户界面开发框架,支持GUI和非GUI程序开发,本文介绍了使用PyQt5进行界面开发的基础知识,包括创建简单窗口、常用控件、窗口属性设... 目录简介第一个PyQt程序最常用的三个功能模块控件QPushButton(按钮)控件QLable(纯文本

SQL Server安装时候没有中文选项的解决方法

《SQLServer安装时候没有中文选项的解决方法》用户安装SQLServer时界面全英文,无中文选项,通过修改安装设置中的国家或地区为中文中国,重启安装程序后界面恢复中文,解决了问题,对SQLSe... 你是不是在安装SQL Server时候发现安装界面和别人不同,并且无论如何都没有中文选项?这个问题也

全面解析HTML5中Checkbox标签

《全面解析HTML5中Checkbox标签》Checkbox是HTML5中非常重要的表单元素之一,通过合理使用其属性和样式自定义方法,可以为用户提供丰富多样的交互体验,这篇文章给大家介绍HTML5中C... 在html5中,Checkbox(复选框)是一种常用的表单元素,允许用户在一组选项中选择多个项目。本

基于Python+PyQt5打造一个跨平台Emoji表情管理神器

《基于Python+PyQt5打造一个跨平台Emoji表情管理神器》在当今数字化社交时代,Emoji已成为全球通用的视觉语言,本文主要为大家详细介绍了如何使用Python和PyQt5开发一个功能全面的... 目录概述功能特性1. 全量Emoji集合2. 智能搜索系统3. 高效交互设计4. 现代化UI展示效果

Python+PyQt5实现MySQL数据库备份神器

《Python+PyQt5实现MySQL数据库备份神器》在数据库管理工作中,定期备份是确保数据安全的重要措施,本文将介绍如何使用Python+PyQt5开发一个高颜值,多功能的MySQL数据库备份工具... 目录概述功能特性核心功能矩阵特色功能界面展示主界面设计动态效果演示使用教程环境准备操作流程代码深度解

Python+PyQt5实现文件夹结构映射工具

《Python+PyQt5实现文件夹结构映射工具》在日常工作中,我们经常需要对文件夹结构进行复制和备份,本文将带来一款基于PyQt5开发的文件夹结构映射工具,感兴趣的小伙伴可以跟随小编一起学习一下... 目录概述功能亮点展示效果软件使用步骤代码解析1. 主窗口设计(FolderCopyApp)2. 拖拽路径

PyQt5 QDate类的具体使用

《PyQt5QDate类的具体使用》QDate是PyQt5中处理日期的核心类,本文主要介绍了PyQt5QDate类的具体使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价... 目录核心功能常用方法及代码示例​1. 创建日期对象​2. 获取日期信息​3. 日期计算与比较​4. 日

Python+PyQt5开发一个Windows电脑启动项管理神器

《Python+PyQt5开发一个Windows电脑启动项管理神器》:本文主要介绍如何使用PyQt5开发一款颜值与功能并存的Windows启动项管理工具,不仅能查看/删除现有启动项,还能智能添加新... 目录开篇:为什么我们需要启动项管理工具功能全景图核心技术解析1. Windows注册表操作2. 启动文件

PyQt5+Python-docx实现一键生成测试报告

《PyQt5+Python-docx实现一键生成测试报告》作为一名测试工程师,你是否经历过手动填写测试报告的痛苦,本文将用Python的PyQt5和python-docx库,打造一款测试报告一键生成工... 目录引言工具功能亮点工具设计思路1. 界面设计:PyQt5实现数据输入2. 文档生成:python-

Python+PyQt5实现多屏幕协同播放功能

《Python+PyQt5实现多屏幕协同播放功能》在现代会议展示、数字广告、展览展示等场景中,多屏幕协同播放已成为刚需,下面我们就来看看如何利用Python和PyQt5开发一套功能强大的跨屏播控系统吧... 目录一、项目概述:突破传统播放限制二、核心技术解析2.1 多屏管理机制2.2 播放引擎设计2.3 专