光标在按钮上时使用mouseMoveEvent()

时间:2018-12-09 14:07:09

标签: python pyqt

当光标移动时,我必须激活某些功能。因此,我在MainWidget中使用了 self.setMouseTracking(True)。但是通过这种方式, mouseMoveEvent()仅在光标下有一个空窗体时才有效。我试图在main上创建另一个小部件,但是它根本不起作用。

updateApplicationContext

该怎么办?

1 个答案:

答案 0 :(得分:0)

如果即使在鼠标放在孩子上方时也要检测鼠标的位置,可能的选择是使用事件过滤器。

from PyQt5 import QtCore, QtGui, QtWidgets

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)

        w_ = QtWidgets.QWidget()
        lay_w = QtWidgets.QHBoxLayout(w_)
        for c in (QtWidgets.QPushButton(), QtWidgets.QLineEdit()):
            lay_w.addWidget(c)

        lay = QtWidgets.QVBoxLayout(self)
        for w in (QtWidgets.QPushButton(), QtWidgets.QLineEdit(), QtWidgets.QTextEdit(), w_):
            lay.addWidget(w)

        for ws in self.findChildren(QtWidgets.QWidget) + [self]:
            ws.setMouseTracking(True)
            ws.installEventFilter(self)

    def eventFilter(self, obj, event):
        if event.type() == QtCore.QEvent.MouseMove:
            p_respect_to_window = self.mapFromGlobal(obj.mapToGlobal(event.pos()))
            print(p_respect_to_window)
        return super(Widget, self).eventFilter(obj, event)


if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

另一方面,如果只想在一种类型的自定义窗口小部件中执行此操作,则最好覆盖自定义窗口小部件的mouseMoveEvent方法:

from PyQt5 import QtCore, QtGui, QtWidgets

class ClickButton(QtWidgets.QPushButton):
    def __init__(self, text, parent=None):
        super(ClickButton, self).__init__(text=text, parent=parent)
        self.setMouseTracking(True)

    def mouseMoveEvent(self, event):
        self.run()
        super(ClickButton, self).mouseMoveEvent(event)

    def run(self):
        print("call to run function in button{} and time: {}".format(self.text(), 
            QtCore.QDateTime.currentDateTime().toString()))

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)

        lay = QtWidgets.QVBoxLayout(self)
        for i in range(10):
            w = ClickButton(str(i), self)
            lay.addWidget(w)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())