import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt
class TreeWidgetDemo(QMainWindow):
def __init__(self, parent=None):
super(TreeWidgetDemo, self).__init__(parent)
self.setWindowTitle('TreeWidget 例子')
self.resize(500,500)
self.attrdict={'人':['行走','静止'],'车':['1','2','3'],'障碍物':['a','b']}
self.listwidget=QListWidget(self)
self.listwidget.adjustSize()
self.tree = QTreeWidget(self)
self.tree.resize(200,200)
self.tree.move(0,200)
# 设置列数
self.tree.setColumnCount(2)
# 设置树形控件头部的标题
self.tree.setHeaderLabels(['attr_level1', 'attr_level2'])
self.tree.setSelectionMode(QAbstractItemView.MultiSelection)
for attr1,attr2s in self.attrdict.items():
father=QTreeWidgetItem(self.tree)
# father.setFlags(father.flags()|Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsAutoTristate)
father.setText(0,attr1)
father.setCheckState(0, Qt.Unchecked)
for attr2 in attr2s:
child=QTreeWidgetItem(father)
# child.setFlags(child.flags()|Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsAutoTristate)
child.setText(1,attr2)
child.setCheckState(1, Qt.Unchecked)
self.tree.itemChanged.connect(self.itemcheckchanged) # itemchanged ---- checkstate 的信号self.onClicked
self.tree.expandAll()
def itemcheckchanged(self,item):
# if item.childCount()>0 and not item.parent():
# self.updatechild(item)
self.updateparent(item)
def updatechild(self):
items = self.tree.findItems('', Qt.MatchContains | Qt.MatchRecursive, 0)
for item in items:
if not item.parent() and item.checkState(0)==Qt.Unchecked:
for i in range(item.childCount()):
item.child(i).setCheckState(1,Qt.Unchecked)
def updateparent(self,item):
parent=item.parent()
if parent:
checkcount=0
itemCount=parent.childCount()
for i in range(itemCount):
item=parent.child(i)
# print(item.checkState(0))
if item.checkState(1)==Qt.Checked:
checkcount+=1
if checkcount<=0:
parent.setCheckState(0,Qt.Unchecked)
else:
parent.setCheckState(0,Qt.Checked)
self.updatechild()
if __name__ == '__main__':
app = QApplication(sys.argv)
tree = TreeWidgetDemo()
tree.show()
sys.exit(app.exec_())
由于没有多级多项选择控件,考虑用treewigget实现,关联一下父子选项