Search code examples
qtmouseeventqtreeviewqtreewidgetselectionmodel

Qt Ignore Right Click in QItemSelectionModel


Is there anyway to detect which mouse button was clicked from inside a QItemSelectionModel?

I want to block a right mouse click from changing the selection.

I am using this was a QTreeWidget, so if there is a way to mask the whole thing, that would be great, but the right-click is still used for context menus, so I didn't pursue this avenue of thought.

Still trying things... I stumbled upon this but I haven't been able to get the function to run: http://qt-project.org/faq/answer/how_to_prevent_right_mouse_click_selection_for_a_qtreewidget This implies a simple override, but this didn't work in Python

def mousePressEvent(self, mouse_event):
    super(MyTreeWidget, self).mousePressEvent(mouse_event)
    print "here %s" % event.type()

Solution

  • This feels like yet another workaround, but I got it working. In this example, the SelectionModel is also an event filter that is getting mouse click events from a QTreeWidget's viewport()

    Also see:

    (Hopefully I didn't leave anything out as I hacked this down on-the-fly, and my real implementation is a little more complex, and uses a separate event filter.)

    from PyQt4.QtGui import QItemSelectionModel
    from PyQt4.QtCore import QEvent
    from PyQt4.QtCore import Qt
    
    # In the widget class ('tree' is the QTreeWidget)...
        # In __init___ ...
            self.selection_model = CustomSelectionModel(self.tree.model())
            self.tree.viewport().installEventFilter(self.selection_model)
    
    # In the selection model...
    class CustomSelectionModel(QItemSelectionModel):
        def __init__(self, model):
            super(CustomSelectionModel, self).__init__(model)
            self.is_rmb_pressed = False
    
        def eventFilter(self, event):
            if event.type() == QEvent.MouseButtonRelease:
                self.is_rmb_pressed = False
            elif event.type() == QEvent.MouseButtonPress:
                if event.button() == Qt.RightButton:
                    self.is_rmb_pressed = True
                else:
                    self.is_rmb_pressed = False
    
        def select(self, selection, selectionFlags):
            # Do nothing if the right mouse button is pressed
            if self.is_rmb_pressed:
                return
    
            # Fall through. Select as normal
            super(CustomSelectionModel, self).select(selection, selectionFlags)