2015-04-01 155 views
1

我想:捕捉鼠标位置(不点击)

 self.installEventFilter(self) 

和:

 desktop= QApplication.desktop() 
     desktop.installEventFilter(self) 

有了:

def eventFilter(self, source, event): 
     if event.type() == QEvent.MouseMove: 
      print(event.pos()) 
     return QMainWindow.eventFilter(self, source, event) 

在QMainWindow的对象,但没有定论。
你有什么想法吗?

回答

2

鼠标事件最初由窗口管理器处理,然后窗口管理器将它们传递到屏幕区域中的任何窗口。因此,如果该地区没有Qt窗口,则不会得到任何事件(包括鼠标事件)。

但是,它仍然有可能通过查询跟踪光标位置:

from PyQt4 import QtCore, QtGui 

class Window(QtGui.QWidget): 
    cursorMove = QtCore.pyqtSignal(object) 

    def __init__(self): 
     super(Window, self).__init__() 
     self.cursorMove.connect(self.handleCursorMove) 
     self.timer = QtCore.QTimer(self) 
     self.timer.setInterval(50) 
     self.timer.timeout.connect(self.pollCursor) 
     self.timer.start() 
     self.cursor = None 

    def pollCursor(self): 
     pos = QtGui.QCursor.pos() 
     if pos != self.cursor: 
      self.cursor = pos 
      self.cursorMove.emit(pos) 

    def handleCursorMove(self, pos): 
     print(pos) 

if __name__ == '__main__': 

    import sys 
    app = QtGui.QApplication(sys.argv) 
    window = Window() 
    window.setGeometry(500, 500, 200, 200) 
    window.show() 
    sys.exit(app.exec_()) 
+0

完美,谢谢 – Mauricio 2015-04-02 06:46:01