Solved QTreeWidgetItem.setItemWidget(item, k, QCheckBox()) not working (checkbox doesn't show up)
-
I'm trying to recursively build a QTreeWidget using a python dictionary. A "[ ]" in a dictionary key/value means add a checkbox. No checkboxes show up no matter what column
k
I add the checkbox to. I also have another solution for adding a checkbox using one and only one column, should I go ahead and use that? It would be nice to have two columns though, since the code is cleaner.from PyQt5.QtWidgets import QTreeWidgetItem, QCheckBox, QDockWidget from PyQt5.QtCore import Qt from ui_cec_spec_filter_dock import Ui_CECSpecFilterDock from collections import OrderedDict HDMI_CEC_Spec = OrderedDict({ "Initiator" : { "TV | [ ]": { "Nibble": "0", "Comment": "", }, "Recording Device 1 | [ ]": { "Nibble": "1", "Comment": "_", }, }, "Follower" : { }, "Command" : { } }) class CECSpecFilterDock(QDockWidget, Ui_CECSpecFilterDock): def __init__(self, new=True): super().__init__() super().__init__() self.setupUi(self) #self.setFocusPolicy(Qt.NoFocus) # BUGFIX: gets rid of weird dotted selection line around tree items self.checkbox = {} if new: self.buildTree(HDMI_CEC_Spec, self.treeWidget.invisibleRootItem()) def buildTree(self, tree, item): if isinstance(tree, dict): for string, subtree in tree.items(): tree_item = self.buildTreeItem(string) item.addChild(tree_item) self.buildTree(subtree, tree_item) else: # expects a string item.addChild(self.buildTreeItem(tree)) def buildTreeItem(self, string): columns = string.split(" | ") tree_item = QTreeWidgetItem() for k in range(0, len(columns)): column = columns[k] if "[ ]" in column or "[*]" in column: self.checkbox[string] = QCheckBox("dur") self.treeWidget.setItemWidget(tree_item, k, self.checkbox[string]) if "*" in column: checkbox.setChecked(True) else: if "_" in column: column = column[:-1] tree_item.setFlags(tree_item.flags() | Qt.ItemIsEditable) tree_item.setText(k, column) return tree_item
-
Fixed it.
You have to make sure that the QTreeWidgetItem is actually in the tree first before calling
setItemWidget
on the tree.