如何创建复选框的树视图?

时间:2014-01-28 09:59:36

标签: python pyqt pyside

如何创建树视图,而pyside上的每个项目都是复选框? 树项是字典,如下例所示:

A: 1: 1.1: 1.1.1
           1.1.2
      1.2: 1.2.1
           1.2.2
   2: 2.1  2.1.1
           2.1.2
B ...

1 个答案:

答案 0 :(得分:4)

试试这个:

import PyQt4.QtGui as gui
import PyQt4.QtCore as core

dat = { 'A': 
            { '1': 
                {'1.1': ['1.1.1', '1.1.2'],
                 '1.2': ['1.2.1', '1.2.2']
                 },            
             '2': 
                {'2.1': ['2.1.1','2.1.2']}
            }
     }

def add(p,ch):
    if isinstance(ch,dict):
        for k,v in ch.iteritems():
            item = gui.QTreeWidgetItem(p)
            item.setText(0, k)
            item.setCheckState(0,core.Qt.Unchecked)
            item.setFlags(core.Qt.ItemIsUserCheckable | core.Qt.ItemIsEnabled)
            add(item,v)
            #p.addChild(item)        
    else:
        for txt in ch:
            item = gui.QTreeWidgetItem(p)
            item.setText(0, txt)
            item.setCheckState(0,core.Qt.Unchecked)
            item.setFlags(core.Qt.ItemIsUserCheckable | core.Qt.ItemIsEnabled)
            #p.addChild(item)        


app = gui.QApplication([])
tw = gui.QTreeWidget()

add(tw,dat)

tw.show()

app.exec_()