0

一位同事制作了一个定制的 QMenu 衍生产品,以便在菜单关闭之前可以选择多个条目。

它是通过 QToolButton 触发的。

问题是如果菜单足够大,它将与按钮重叠。单击 QToolButton 时,当前光标位置的项目会立即被选中。

如何防止这种情况发生?

我的菜单代码,我试图忽略第一个带有 Bool 标志的事件,但它不起作用。

class StayOpenMenu(QMenu):
    """
    a class that overrides the QMenu mouseReleaseEvent to let the menu stay open when an element is selected
    """
    def __init__(self, parent=None):
        self.isfirstEvent = True
        super().__init__("Stay open Menu", parent=parent)

    def mouseReleaseEvent(self, a0: QMouseEvent):
        if self.isfirstEvent:
            a0.ignore()
            self.isfirstEvent = False
            return
        try:
            action = self.actionAt(a0.pos())
            action.trigger()
        except:
            pass
    
    def aboutToShow(self):
        self.isfirstEvent = True
        return super().aboutToShow()

    def aboutToHide(self):
        self.isfirstEvent = True
        return super().aboutToShow()

图片:点击按钮之前

图片:点击 QToolButton 后

4

1 回答 1

0

aboutToShow()并且aboutToHide()信号,而不是方法,因此它们不能被“覆盖”。

创建一个用于将变量设置为 True 的插槽并将其仅连接到aboutToShow信号。
另请注意,您还必须注意 mousePressEvent:如果未通过鼠标单击激活菜单(很可能是通过键盘按下工具按钮),它将阻止它接收合法的释放事件。

class StayOpenMenu(QMenu):
    def __init__(self, parent=None):
        self.isfirstEvent = False
        super().__init__("Stay open Menu", parent=parent)
        self.aboutToShow.connect(self.isShowing)

    def isShowing(self):
        self.isfirstEvent = True

    def mousePressEvent(self, a0: QMouseEvent):
        self.isfirstEvent = False
        super().mousePressEvent(a0)

    def mouseReleaseEvent(self, a0: QMouseEvent):
        if self.isfirstEvent:
            a0.ignore()
            self.isfirstEvent = False
            return
        try:
            action = self.actionAt(a0.pos())
            action.trigger()
        except:
            pass
于 2020-01-24T12:44:37.967 回答