axure實現複選框全選_Pyqt5自定義控制元件帶全選功能的複選框
阿新 • • 發佈:2021-01-08
技術標籤:axure實現複選框全選
本篇的例子實現了一個帶全選功能的複選框:
#自定義控制元件--實現了一個帶全選功能的複選框import sysfrom PyQt5.QtWidgets import QApplication, QListWidget, QCheckBox,QListWidgetItemfrom PyQt5.QtCore import Qtclass FilteredList(QListWidget):#繼承自列表控制元件 def __init__(self, textList, parent=None): super().__init__(parent) self.selectAll_ch = QCheckBox("全選(selectAll)") self.selectAll_ch.setCheckState(Qt.Checked) self.selectAll_ch.stateChanged[int].connect(self.on_selectAll)# item = QListWidgetItem(self)self.setItemWidget(item,self.selectAll_ch)#列表控制元件的項設為 QCheckBox self.dict = dict() self.boxes = set() for index, text in enumerate(textList): ch = QCheckBox(text) ch.setCheckState(Qt.Unchecked) ch.stateChanged[int].connect(self.on_stateChanged) #item.setCheckState(Qt.Unchecked)# item = QListWidgetItem(self) self.setItemWidget(item, ch) self.boxes.add(ch) self.dict[index] = ch def on_selectAll(self,state): if state == 2: for ch in self.boxes: ch.setCheckState(2) if state == 0: for ch in self.boxes: ch.setCheckState(0) def on_stateChanged(self,state): ch = self.sender() if state: if len([ch for ch in self.boxes if ch.checkState()]) == self.count()-1: #0 不選中, 1 部分選中,2 全選中 #Qt.Unchecked #Qt.PartiallyChecked #Qt.Checked self.selectAll_ch.setCheckState(2) else: self.selectAll_ch.setCheckState(1) else: if len([k for k in self.boxes if k.checkState()]): 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=["a","b","c","d"]) myList.show()sys.exit(app.exec_())