Search code examples
pythonpyqtqtreewidget

Context menu only for QTreeWidget children


I would like to show a context Menu in a QTreeWidget only for child items. For the moment, I am getting the index with the following function:

def menuItem(self,pos):
    index = self.ui.tree.indexAt(pos)

    if not index.isValid():
        return 

    menu = QtGui.QMenu(self)
    menu.addAction("Action 1")
    menu.addAction("Action 2")
    menu.exec_(QtGui.QCursor.pos())

But I would need to know if this index is a children one. Any suggestion?


Solution

  • Top-level items will have invalid index for their parents. You can include that in your check:

    if not index.isValid() or not index.parent().isValid():
        return