pyqt事件过滤器的使用(eventFilter)
# -*- coding: cp936 -*-
#由于现在不是很明白:事件过滤器的使用(eventFilter),先收藏着
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)
self.edit.installEventFilter(self)#在窗体上为self.edit安装过滤器
#QEvent::FocusIn(获得焦点事件)
"""
QPalette p=QPalette();
p.setColor(QPalette::Base,Qt::green);
ui->lineEdit1->setPalette(p);
QEvent::FocusOut失去焦点
"""
self.list.installEventFilter(self)
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_())