Here, we take the simpletreemode. pyw file in the python built-in demo as an example to briefly introduce how to use checkbox in the Treeview of pyqt. All the work is actually done in the treemodel class.
First, add self. checklisk = [] to the _ init _ function of the treemodel class, and define a list to save the selected checkbox information.
Step 2: Modify the Flag Function
Def flags (self, index): <br/> if not index. isValid (): <br/> return QtCore. qt. noItemFlags <br/> result = QtCore. qt. itemIsEnabled | QtCore. qt. itemIsSelectable <br/> if index. column () = 0: # only display checkbox in the first column <br/> result | = QtCore. qt. itemIsUserCheckable <br/> return result
This mainly adds an itemisusercheckable for the display method in the first example.
Then, modify the data function as follows:
Def data (self, index, role): <br/> if not index. isValid (): <br/> return None </p> <p> item = index. internalPointer () </p> <p> if role = QtCore. qt. checkStateRole: # The selected item is checkbox <br/> if item. parent () = self. rootItem: # return <br/> return None <br/> if item. childCount ()> 0: # if there is a subitem, return directly. This can be adjusted as needed. You must retain <br/> return None <br/> if index. column () = 0: <br/> for x in self. checkLisk: # Check whether the item is in the checkList. if you set it to the selected status <br/> if x = index: <br/> return QtCore. qt. checked <br/> else: <br/> return QtCore. qt. unchecked <br/> if role! = QtCore. Qt. DisplayRole: <br/> return None <br/> return item. data (index. column ())
Add the setdata function in simpletreemodel. pyw does not exist. It is a function defined in qiniactitemmodel. When the item in treemodel changes, this function is called and a datachanged signal is required. In this function, you need to determine whether the changed Project is a checkbox and modify the checklist based on the changes. Then send the datachanged signal. Although I don't know what the slot functions of datachange do, it certainly calls the corresponding data function. Then, it will reset the content of the check box just clicked.
Def setData (self, index, value, role = QtCore. qt. editRole): <br/> if role = QtCore. qt. checkStateRole and index. column () = 0: <br/> if value = QtCore. qt. unchecked: # uncheckable <br/> self. checkLisk. remove (index) # remove the node index from the checklist <br/> self. emit (QtCore. SIGNAL ("dataChanged (QModelIndex, QModelIndex)"), <br/> index, index) <br/> else: # selected <br/> self. checkLisk. append (index) # Add the node index to the checklist <br/> self. emit (QtCore. SIGNAL ("dataChanged (QModelIndex, QModelIndex)"), <br/> index, index) <br/> return True
Code in http://download.csdn.net/source/3019094