本篇的例子实现了一个带搜索和全选功能的复选框。搜索时不区分大小写。可通过"/"设置搜索多个内容。按回车键开始搜索。
源码如下:
import sys
from PyQt5.QtWidgets import QApplication, QListWidget, QLineEdit, QCheckBox, QListWidgetItem
from PyQt5.QtCore import Qt
class FilteredList(QListWidget):
#继承自列表控件
def __init__(self, textList, parent=None):
super().__init__(parent)
search = QLineEdit("搜索")
search.selectAll()
search.returnPressed.connect(self.on_return) # 检测回车信号
search.setToolTip('不区分大小写搜索。可通过"/"设置搜索多个内容')
search.setToolTipDuration(1000) # 1000ms
item = QListWidgetItem(self)
self.setItemWidget(item, search )#列表控件的首项 设为 QlineEdit
self.selectAll_ch = QCheckBox("全选(selectAll)")
self.selectAll_ch.setChecked(False)
self.selectAll_ch.stateChanged[int].connect(self.on_selectAll)#
item = QListWidgetItem(self)
self.setItemWidget(item, self.selectAll_ch )#列表控件的项设为 QCheckBox
# setCheckState 方法用于设置 QCheckBox 的状态为选中(Qt.Checked)、半选中( Qt.PartiallyChecked)或未选中(Qt.Unchecked)
self.boxes = []
for index, text in enumerate(textList):
ch = QCheckBox(text)
ch.setTristate(False)
ch.setChecked(False)
ch.stateChanged[int].connect(self.on_stateChanged)
item = QListWidgetItem(self)
self.setItemWidget(item, ch)
self.boxes.append(ch)
self.checkedQty = 0
self.count = len(textList)
# / 如果想要通过代码改变QCheckBox的状态,同时不触发槽函数,
# // 可以简单地阻塞信号,并且之后重新启用它们
# checkBox->blockSignals(true);
# checkBox->setCheckState(Qt::Checked);
# checkBox->blockSignals(false);
def on_return(self):
# print("enter pressed")
text = self.sender().text()
if text == "":
return
for ch in self.boxes:
ch.setChecked(False)
for string in text.upper().split("/"):
for ch in self.boxes:
if ch.text().upper().find(string) != -1:
ch.setChecked(True)
def on_selectAll(self, state):
#for ch in self.findChildren(QCheckBox):
#print(ch)
if state == 0:
for ch in self.boxes:
ch.setChecked(False)
self.checkedQty = 0
elif state == 2:
for ch in self.boxes:
ch.setChecked(True)
self.checkedQty = self.count
def on_stateChanged(self, state): # state 传入的是改变后的状态. #0 不选中, 1 部分选中,2 全选中
# print(state, self.count, self.checkedQty)
# ch = self.sender()
if state:
self.checkedQty += 1
if self.checkedQty == self.count:
self.selectAll_ch.setCheckState(2)
else:
self.selectAll_ch.setCheckState(1)
else: # state == 0
self.checkedQty -= 1
if self.checkedQty > 0:
self.selectAll_ch.setCheckState(1)
else:
self.selectAll_ch.setCheckState(0)
def keyPressEvent(self, event):
#Ctrl+A 全选
if event.modifiers() & Qt.ControlModifier and event.key()==Qt.Key_A:
self.selectAll_ch.setCheckState(2)
if __name__ == '__main__':
app = QApplication(sys.argv)
myList = FilteredList(textList=["张三","李四","王五","赵六"])
myList.show()
sys.exit(app.exec_())
本文分享自 Python可视化编程机器学习OpenCV 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!