Search code examples
pythonselectionpysideqtreewidget

Disable selection of parent rows in a QTreeWidget


I populate nested lists in a QTreeWidget, and I need to disable the selection of parent rows.

The code is:

def fillTree(self):
    '''
    Fill UI with list of parts
    '''
    roots = ['APLE', 'ORANGE', 'MANGO']
    childs = ['body', 'seed', 'stern']
    parent = self.treeWidget.invisibleRootItem()
    for root in roots:
        widgetTrim = QTreeWidgetItem()
        widgetTrim.setText(0, root)
        parent.addChild(widgetTrim)
        for child in childs:
            widgetPart = QTreeWidgetItem()
            widgetPart.setText(0, child)
            widgetTrim.addChild(widgetPart)

enter image description here

I need to avoid selection of the "fruit" items.


Solution

  • You must remove Qt.ItemIsSelectable from the item-flags:

    widgetTrim = QTreeWidgetItem()
    widgetTrim.setFlags(widgetTrim.flags() & ~Qt.ItemIsSelectable)
    

    The flags are an OR'd together combination ItemFlag values. So a bitwise AND NOT operation is used to remove the ItemIsSelectable from the existing combination of flags.