# -*- coding: utf-8 -*-
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class TreeWidget(QWidget):
def __init__(self):
super(TreeWidget, self).__init__()
self.setWindowTitle('TreeWidget')
self.tree = QTreeWidget() # 实例化一个TreeWidget对象
self.tree.setColumnCount(2) # 设置部件的列数为2
self.tree.setDropIndicatorShown(True)
self.tree.setSelectionMode(QAbstractItemView.ExtendedSelection)#设置item可以多选
self.tree.setHeaderLabels(['Key', 'Value']) # 设置头部信息对应列的标识符
# 设置root为self.tree的子树,故root是根节点
root = QTreeWidgetItem(self.tree)
root.setText(0, 'root') # 设置根节点的名称
# 为root节点设置子结点
child1 = QTreeWidgetItem(root)
child1.setText(0, 'child1')
child1.setText(1, 'name1')
child1.setCheckState(0, Qt.Unchecked);
child2 = QTreeWidgetItem(root)
child2.setText(0, 'child2')
child2.setText(1, 'name2')
child2.setCheckState(0, Qt.Unchecked);
child3 = QTreeWidgetItem(root)
child3.setText(0, 'child3')
child3.setCheckState(0, Qt.Unchecked);
child4 = QTreeWidgetItem(child3)
child4.setText(0, 'child4')
child4.setText(1, 'name4')
child4.setCheckState(0, Qt.Unchecked);
button=QPushButton("test")
lay=QVBoxLayout()
lay.addWidget(button)
lay.addWidget(self.tree)
button.clicked.connect(self.getText)
self.tree.itemChanged.connect(self.handleChanged)
self.tree.addTopLevelItem(root)
self.setLayout(lay) # 将tree部件设置为该窗口的核心框架
def handleChanged(self, item, column):
#当check状态改变时得到他的状态。
if item.checkState(column) == Qt.Checked:
print "checked", item, item.text(column)
if item.checkState(column) == Qt.Unchecked:
print "unchecked", item, item.text(column)
def getText(self):
#print self.tree
#获取选择的某项
#print self.tree.currentItem().text(1) ;
#当item多选时获取选择的某几项,text(0),代表第0列,text(1),代表第1列
Item_list= self.tree.selectedItems ()
for ii in Item_list:
print ii.text(1)
app = QApplication(sys.argv)
app.aboutToQuit.connect(app.deleteLater)
tp = TreeWidget()
tp.show()
app.exec_()
获取是否选中的另一种方法
def find_checked(self):
checked = dict()
#list_all=[]
root = self.tree.invisibleRootItem()
signal_count = root.childCount()
for i in range(signal_count):
signal = root.child(i)
checked_sweeps = list()
num_children = signal.childCount()
for n in range(num_children):
child = signal.child(n)
if child.checkState(0) == Qt.Checked:
checked_sweeps.append(child.text(0))
#list_all.append(child.text(0))
#list_all.append(str(child.text(0)))
checked[signal.text(0)] = checked_sweeps
#print checked.keys()[0]
#print checked[checked.keys()[0]]
return checked