您必须实现该eventFilter
方法并将此属性启用到所需的小部件:
{your widget}.installEventFilter(self)
eventFilter方法具有事件的对象和类型作为信息.
例
import sys from PyQt5 import uic from PyQt5.QtCore import QEvent from PyQt5.QtWidgets import QApplication, QWidget uiFile = "widget.ui" # Enter file here. Ui_Widget, _ = uic.loadUiType(uiFile) class Widget(QWidget, Ui_Widget): def __init__(self, parent=None): super(Widget, self).__init__(parent=parent) self.setupUi(self) self.lineEdit.installEventFilter(self) self.pushButton.installEventFilter(self) self.comboBox.installEventFilter(self) def eventFilter(self, obj, event): if event.type() == QEvent.FocusIn: if obj == self.lineEdit: print("lineedit") elif obj == self.pushButton: print("pushbutton") elif obj == self.comboBox: print("combobox") return super(Widget, self).eventFilter(obj, event) if __name__ == '__main__': app = QApplication(sys.argv) w = Widget() w.show() sys.exit(app.exec_())
输出继电器:
lineedit pushbutton combobox pushbutton lineedit