import sys
from PyQt5.Qt import *
# 自定义类,继承类QApplication
class CustomApplication(QApplication):
# 重写QApplication的notify方法
def notify(self, a0, a1) -> bool:
# 捕获receiver为QPushButton,事件为QEvent.MouseButtonPress的事件
if a0.inherits("QPushButton") and a1.type() == QEvent.MouseButtonPress:
print(a0, a1, "notify-按钮按下了!")
return QApplication.notify(self, a0, a1)
class CustomButton(QPushButton):
def event(self, e) -> bool:
if e.type() == QEvent.MouseButtonPress:
print(e, "event-按钮按下了!")
return QPushButton.event(self, e)
def mousePressEvent(self, e) -> None:
print(e, "mousePressEvent-按钮按下了!")
# mousePressEvent无返回值,所以调用父方法即可,无需返回值
QPushButton.mousePressEvent(self, e)
class Window(QWidget):
def __init__(self):
super().__init__()
self.label_1 = QLabel()
self.button_1 = QPushButton()
self.set_ui()
def set_ui(self):
self.resize(300, 300)
self.setStyleSheet("color:blue")
self.setWindowTitle("主窗口")
self.label()
self.button()
self.action()
self.show()
def label(self):
self.label_1 = QLabel(self)
self.label_1.setText("Hello")
self.label_1.move(100, 100)
def button(self):
self.button_1 = CustomButton(self)
self.button_1.setText("按下试试")
self.button_1.move(100, 200)
def action(self):
self.button_1.clicked.connect(self.push_button)
def push_button(self):
self.label_1.setText("World!")
self.label_1.adjustSize()
if __name__ == '__main__':
app = CustomApplication(sys.argv)
window = Window()
sys.exit(app.exec_())