How to create a treeview of checkboxes?

2019-06-11 10:40发布

问题:

How to create a tree view, while each item on the is checkbox in pyside? The tree items are dictionary that look like the example below:

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:

Try this:

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_()