这感觉像是另一种解决方法,但我得到了它的工作。在这个例子中,SelectionModel 也是一个事件过滤器,它从 QTreeWidget 的 viewport() 获取鼠标点击事件
另见:
(希望我没有遗漏任何东西,因为我在运行中破解了它,而我的实际实现要复杂一些,并使用单独的事件过滤器。)
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)