Pyqt 鼠标悬停在 QPushButton 上

kal*_*gne 5 python events pyqt4 python-2.7

我想检测鼠标在QPushButton. 为此,我在按钮上安装了一个事件过滤器。但是,MouseMove当鼠标悬停在按钮上时,事件不会完全触发。当我单击与前一个位置不同的位置上的按钮时,似乎有时会触发它。简单地说:我将鼠标移到按钮上:没有任何反应。我点击:MouseButtonPressed事件被触发。我将鼠标移动到按钮上的另一个位置:没有任何反应。我再次点击:也MouseButtonPressed被触发MouseMove了。

我想在每次鼠标悬停按钮时触发 MouseMove。我该怎么办?

这是我的代码:

import sys

from PyQt4 import QtCore
from PyQt4.QtGui import *

class eventFilterWindow(QMainWindow):

    def __init__(self):
        QMainWindow.__init__(self)
        widget = QWidget()

        button = QPushButton("Trigger event!")
        button.installEventFilter(self)

        hbox = QHBoxLayout()
        hbox.addWidget(button)
        widget.setLayout(hbox)
        self.setCentralWidget(widget)
        self.show()

    def eventFilter(self, object, event):

        if event.type() == QtCore.QEvent.MouseButtonPress:
            print "You pressed the button"
            return True

        elif event.type() == QtCore.QEvent.MouseMove:
            print "C'mon! CLick-meeee!!!"
            return True

        return False

def main():
    app = QApplication(sys.argv)
    #myWindow = EventsWindow()
    window = eventFilterWindow()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()
Run Code Online (Sandbox Code Playgroud)

编辑:

实际上,MouseMoveQPushButton按下 的同时移动鼠标时会触发。

kal*_*gne 5

我找到了答案。当我搜索包含该关键字的事件时,我被误导了Mouse。我正在寻找的事件实际上是QtCore.QEvent.HoverMove.

  • 您还可以使用 QPushButton.enterEvent 和 QPushButton.leaveEvent。看看他们 (5认同)