python - 没有 MousePress 的 PyQt4 MouseMove 事件

标签 python pyqt mouseevent pyqt4 mouseover

我需要捕捉用户将鼠标移到 GUI 上的时间,而不是他们按住鼠标按钮的时间(这会做一些不同的事情)。

我找不到任何方便的方法来做到这一点, 除了定期找到鼠标位置并将其检查到它以前的位置...... 这会很糟糕。

mouseMoveEvent 仅在按下鼠标左键的同时移动鼠标时调用, 除非小部件当然有“鼠标跟踪”。鼠标跟踪对我来说不是一个选项,因为当移动鼠标和按下鼠标左键时,GUI 的行为必须不同。

是否有任何内置方法可以做到这一点? (或者只是任何聪明的想法?)

例如: 有没有办法随时检查鼠标左键是否被按下?
或者可以应用于 QRect(坐标)的“鼠标悬停”事件?

非常感谢。


Windows 7 (32)
python 2.7
PyQt4

最佳答案

最直接的方法是在 qApp 上安装事件过滤器:

from PyQt4 import QtGui, QtCore

class Window(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        widget = QtGui.QWidget(self)
        layout = QtGui.QVBoxLayout(widget)
        self.edit = QtGui.QLineEdit(self)
        self.list = QtGui.QListWidget(self)
        layout.addWidget(self.edit)
        layout.addWidget(self.list)
        self.setCentralWidget(widget)

    def eventFilter(self, source, event):
        if event.type() == QtCore.QEvent.MouseMove:
            if event.buttons() == QtCore.Qt.NoButton:
                pos = event.pos()
                self.edit.setText('x: %d, y: %d' % (pos.x(), pos.y()))
            else:
                pass # do other stuff
        return QtGui.QMainWindow.eventFilter(self, source, event)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    win = Window()
    win.show()
    app.installEventFilter(win)
    sys.exit(app.exec_())

关于python - 没有 MousePress 的 PyQt4 MouseMove 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7829829/

相关文章:

python - 从非类函数调用类中的函数

python - 是否可以将 QTableWidget 水平添加到布局中?

python - 我可以在 Mac OS X 上的哪里保存 Python 开发的 GUI 应用程序的 sqlite 数据库?

c# - wpf 窗口边界外的光标移动事件

python - 在 Python 中将半精度(2 字节)转换为 Float

python - 重新采样 Pandas 时间序列以获得 bin 名称的结束时间戳?

c++ - SFML 输入 GetMouseX 和 GetMouseY 未捕捉到鼠标移动

c++ - 获取 QImage 中的鼠标位置

python - 在 PyQt 中将 QstringList 转换为 Qstring

python - 在 QVBoxLayout 中添加 QStatusBar