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

相关文章

全面解析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 专

使用PyQt5编写一个简单的取色器

《使用PyQt5编写一个简单的取色器》:本文主要介绍PyQt5搭建的一个取色器,一共写了两款应用,一款使用快捷键捕获鼠标附近图像的RGB和16进制颜色编码,一款跟随鼠标刷新图像的RGB和16... 目录取色器1取色器2PyQt5搭建的一个取色器,一共写了两款应用,一款使用快捷键捕获鼠标附近图像的RGB和16

【Python篇】PyQt5 超详细教程——由入门到精通(终篇)

文章目录 PyQt5超详细教程前言第9部分:菜单栏、工具栏与状态栏9.1 什么是菜单栏、工具栏和状态栏9.2 创建一个简单的菜单栏示例 1:创建带有菜单栏的应用程序代码详解: 9.3 创建工具栏示例 2:创建带有工具栏的应用程序代码详解: 9.4 创建状态栏示例 3:创建带有状态栏的应用程序代码详解: 9.5 菜单栏、工具栏与状态栏的结合示例 4:完整的应用程序界面代码详解: 9.6 总结