Search code examples
qteventspyqtmouseqtreewidget

How to disable right click in a QTreeWidget in PyQt?


I have a QTreeWidget where I want to disable right click on the item. Currently I am using itemClicked signal to detect clicks on children of the treeWidget, but I only want to do something when the user left clicks an item and do nothing on right click. Both left and right clicks are getting detected right now and I am not able to differentiate between the two. Thanks in advance!


Solution

  • You can reimplement the treewidget's mouse release event:

    class TreeWidget(QtGui.QTreeWidget):    
        def mouseReleaseEvent(self, event):
            if event.button() != QtCore.Qt.RightButton:
                super(TreeWidget, self).mouseReleaseEvent(event)
    

    or install an event-filter on the treewidget's viewport:

    class MainWindow(QtGui.QMainWindow):
        def __init__(self):
            ...
            self.tree = QtGui.QTreeWidget(self)
            self.tree.viewport().installEventFilter(self)
    
        def eventFilter(self, source, event):
            if (event.type() == QtCore.QEvent.MouseButtonRelease and
                event.button() == QtCore.Qt.RightButton and
                source is self.tree.viewport()):
                return True
            return super(Window, self).eventFilter(source, event)