mylineedit.py
from PyQt5.QtWidgets import * import PyQt5.QtCore class MyLineEdit(QLineEdit): def __init__(self, parent = None): super(QLineEdit,self).__init__(parent) def keyPressEvent(self, QKeyEvent): print(self.tr('MylineEdit键盘按下事件')) super().keyPressEvent(QKeyEvent) QKeyEvent.ignore() def event(self, event): if event.type() == PyQt5.QtCore.QEvent.KeyPress: print(self.tr('MyLineEdit的event()函数')) return super().event(event)
widget.py
from PyQt5.QtWidgets import * import PyQt5.QtCore from PyQt5.QtCore import QTimer from PyQt5.QtGui import QPalette, QColor, QFont import sys import mylineedit class Widget(QWidget): def __init__(self, parent = None): super(QWidget, self).__init__(parent) self.setWindowTitle(self.tr('事件传递顺序')) self.setFixedSize(200,200) self.lineEdit = mylineedit.MyLineEdit(self) self.lineEdit.installEventFilter(self) self.lineEdit.setFixedSize(200,30) self.lineEdit.setStyleSheet('color:red') self.lineEdit.setStyleSheet('background-color:green') font = QFont() font.setFamily('楷体') #设置字体 font.setBold(True) #设置粗体 font.setItalic(True)#设置斜体 font.setPixelSize(20) font.setPointSize(25) font.setCapitalization(QFont.Capitalize)#首字母大写 self.lineEdit.setFont(font)#将font应用到lineEdit self.label = QLabel(self.tr('文本编辑器'),self) palette = QPalette() palette.setColor(QPalette.Background, QColor(0,255,0)) self.label.setAutoFillBackground(True) self.label.setPalette(palette) self.h_layout = QHBoxLayout() self.h_layout.addWidget(self.label) self.h_layout.addWidget(self.lineEdit) self.setLayout(self.h_layout) self.timer = QTimer() self.timer.timeout.connect(self.timeOut) self.timer.start(1000) def keyPressEvent(self, QKeyEvent): print(self.tr('Widget键盘按下事件')) def eventFilter(self, obj, event): if obj == self.lineEdit: if event.type() == PyQt5.QtCore.QEvent.KeyPress: print(self.tr('Widget的事件过滤器')) return super().eventFilter(obj, event) def timeOut(self): print(self.tr('时间到')) if __name__ == '__main__': app = QApplication(sys.argv) widget = Widget() widget.show() print(widget.children()) sys.exit(app.exec_())