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

相关文章

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 总结

OpenStack:Glance共享与上传、Nova操作选项解释、Cinder操作技巧

目录 Glance member task Nova lock shelve rescue Cinder manage local-attach transfer backup-export 总结 原作者:int32bit,参考内容 从2013年开始折腾OpenStack也有好几年的时间了。在使用过程中,我发现有很多很有用的操作,但是却很少被提及。这里我暂不直接

OpenStack实例操作选项解释:启动和停止instance实例

关于启动和停止OpenStack实例 如果你想要启动和停止OpenStack实例时,有四种方法可以考虑。 管理员可以暂停、挂起、搁置、停止OpenStack 的计算实例。但是这些方法之间有什么不同之处? 目录 关于启动和停止OpenStack实例1.暂停和取消暂停实例2.挂起和恢复实例3.搁置(废弃)实例和取消废弃实例4.停止(删除)实例 1.暂停和取消暂停实例

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

文章目录 PyQt5超详细教程前言第7部分:生成图表与数据可视化7.1 matplotlib 与 PyQt5 的结合7.2 在 PyQt5 中嵌入 matplotlib 图表示例 1:嵌入简单的 matplotlib 图表代码详解: 7.3 动态生成图表示例 2:动态更新图表代码详解: 7.4 在应用程序中展示不同类型的图表示例 3:展示不同类型的图表代码详解: 7.5 总结 第8部分:对话

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

文章目录 PyQt5 超详细入门级教程前言序篇:1-3部分:PyQt5基础与常用控件第1部分:初识 PyQt5 和安装1.1 什么是 PyQt5?1.2 在 PyCharm 中安装 PyQt51.3 在 PyCharm 中编写第一个 PyQt5 应用程序1.4 代码详细解释1.5 在 PyCharm 中运行程序1.6 常见问题排查1.7 总结 第2部分:创建 PyQt5 应用程序与布局管理2

【YOLO 系列】基于YOLOV8的智能花卉分类检测系统【python源码+Pyqt5界面+数据集+训练代码】

前言: 花朵作为自然界中的重要组成部分,不仅在生态学上具有重要意义,也在园艺、农业以及艺术领域中占有一席之地。随着图像识别技术的发展,自动化的花朵分类对于植物研究、生物多样性保护以及园艺爱好者来说变得越发重要。为了提高花朵分类的效率和准确性,我们启动了基于YOLO V8的花朵分类智能识别系统项目。该项目利用深度学习技术,通过分析花朵图像,自动识别并分类不同种类的花朵,为用户提供一个高效的花朵识别

纯css实现checkbox的checked样式

纯css也能实现checked样式 今天使用微信的WEUI的checkbox的时候,发现点击checkbox是有checked和unchecked的变化的,但是想要去获得checkbox的checked状态时,发现event listener里居然没有该checkbox的click之类的事件。这才发现,weui只是纯粹的css样式,没有对应组件的js代码。那么问题来了,没有js事件,weui是如

查看Excel 中的 Visual Basic 代码,要先设置excel选项

1. excel VB的简单介绍 百度安全验证 2.excel选项设置 excel表格中在选项->自定义功能区域,选择开发工具,visual baisc/查看代码,即可看到代码。 3.excel已经设置,可以直接查看