问题描述:

For some reason, whenever the menu-button part of the QToolButton gets clicked, it generates a momentary leaveEvent (at least when it is in a toolbar). I even tested underMouse() in the leaveEvent, and it returns false. Why is this? Is there a way to fix this?

Sample for testing (Py3.3, change super() for py2.7):

from PyQt4.QtGui import *

class MainWindow(QMainWindow):

def __init__(self):

super().__init__()

toolbar = QToolBar(self)

toolbar.addWidget(ToolButton())

class ToolButton(QToolButton):

def __init__(self, parent=None):

super().__init__(parent)

self.setText('test')

self.setPopupMode(QToolButton.MenuButtonPopup)

self.setMenu(QMenu())

self.menu().addAction('Stub')

def enterEvent(self, event):

print('entered')

super().enterEvent(event)

def leaveEvent(self, event):

print('left')

super().leaveEvent(event)

if __name__ == '__main__':

import sys

application = QApplication(sys.argv)

window = MainWindow()

window.show()

sys.exit(application.exec_())

网友答案:

The following can be used to double check; unlike leaveEvent, it always returns the correct information:

def leaveEvent(self, event):
    if not QApplication.widgetAt(QCursor().pos()) is self:
        #do stuff
    super().leaveEvent(event)
相关阅读:
Top