使用PyQT,如何使用自定义列表过滤带有QComboBox的mousePressEvent
题
我有一个带有自定义列表对象的 QComboBox
。
自定义列表对象具有自定义 mousePressEvent
,因此当用户点击其中一个带有+/-(曲折)的圆圈时,列表将展开/折叠。
当我使用带有组合框的列表时,当用户点击曲折时,列表会展开/折叠,但选择会更改,并且列表会被隐藏。如何对此进行过滤,以便当用户点击曲折时,选择不会更改,并且列表不会隐藏。
其他屏幕截图
所有节点都已崩溃:
隐藏列表:
解决方案
QT有一个 eventFilter
,可以“捕获” <代码> QEvent.MouseButtonRelease 代码>。所以我所做的就是安装我自己的 eventFilter
,如果用户点击某个节点,它会过滤 QEvent.MouseButtonRelease
事件。
在我的列表对象中,我有以下方法:
def mousePressEvent (self, e):
self.colapse_expand_click = False
if <user clicked node>:
colapse_expand_node()
e.accept ()
self.colapse_expand_click = True
mousePressEvent
在 mouseReleaseEvent
之前运行。
然后在自定义组合框中,我过滤了事件:
class RevisionSelectorWidget(QtGui.QComboBox):
def __init__(self, parent = None):
QtGui.QComboBox.__init__(self, parent)
self.log_list = RevisionSelectorLogList(self)
self.setView(self.log_list)
self.log_list.installEventFilter(self)
self.log_list.viewport().installEventFilter(self)
def eventFilter(self, object, event):
if event.type() == QtCore.QEvent.MouseButtonRelease:
if self.log_list.colapse_expand_click:
return True
return False
其他提示
在我的脑海中,您可以继承 QComboBox
并覆盖 hideEvent(QHideEvent)
(继承自 QWidget
)
def hideEvent(self, event):
if self.OkToHide():
event.accept()
else:
event.ignore()
你的截图看起来像是一个有趣的组合框使用,我很好奇为什么你没有使用 TreeView
样式控件而不是列表?
编辑(2009年3月14日):
我查看了Qt源代码,看起来当捕获键盘和鼠标事件时,qt一旦决定发出&quot; activated(int index)&quot;
信号,&quot; hidePopup()&quot;
已被调用。
除了重写他们的事件过滤器代码之外,另一个选择是连接&quot; activated(int index)&quot;
或&quot; highlight(int index)&quot;
发信号到一个可以调用&quot; showPopup()&quot;
的插槽,它会重新提升列表项。如果你得到一个令人讨厌的消失/出现油漆问题,你可能必须让Qt延迟油漆事件,同时弹出窗口可见。
希望有所帮助!