本文展示了 pyqt5 信号槽的装饰器实现方式(借鉴自 eirc6)
一个简单的例子。实现功能:两个数相加,显示结果。如图
两个文件,第一个是界面文件 ui_calc.py
# ui_calc.py from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Calc(object): def setupUi(self, Form): self.inputSpinBox1 = QtWidgets.QSpinBox(Form) self.inputSpinBox1.setGeometry(QtCore.QRect(1, 26, 46, 25)) self.inputSpinBox1.setObjectName("inputSpinBox1") # 必须 self.inputSpinBox2 = QtWidgets.QSpinBox(Form) self.inputSpinBox2.setGeometry(QtCore.QRect(70, 26, 46, 25)) self.inputSpinBox2.setObjectName("inputSpinBox2") # 必须 self.outputWidget = QtWidgets.QLabel(Form) self.outputWidget.setGeometry(QtCore.QRect(140, 24, 36, 27)) self.outputWidget.setObjectName("outputWidget") # 必须 QtCore.QMetaObject.connectSlotsByName(Form) # 必须
说明:1. 界面部件需要setObjectname ; 2. 最后必须 QtCore.QMetaObject.connectSlotsByName(Form)
第二个是逻辑文件 calc.py
# calc.py
from PyQt5.QtCore import pyqtSlot from PyQt5.QtWidgets import QApplication, QWidget from ui_calc import Ui_Calc
# 方式一 class MyCalc(QWidget): def __init__(self, parent=None): super().__init__(parent) self.ui = Ui_Calc() self.ui.setupUi(self) @pyqtSlot(int) def on_inputSpinBox1_valueChanged(self, value): self.ui.outputWidget.setText(str(value + self.ui.inputSpinBox2.value())) @pyqtSlot(int) def on_inputSpinBox2_valueChanged(self, value): self.ui.outputWidget.setText(str(value + self.ui.inputSpinBox1.value()))
# 方式二 class MyCalc2(QWidget, Ui_Calc): def __init__(self, parent=None): super().__init__(parent) self.setupUi(self) @pyqtSlot(int) def on_inputSpinBox1_valueChanged(self, value): self.outputWidget.setText(str(value + self.inputSpinBox2.value())) @pyqtSlot(int) def on_inputSpinBox2_valueChanged(self, value): self.outputWidget.setText(str(value + self.inputSpinBox1.value()))
if __name__ == '__main__': import sys app = QApplication(sys.argv) win = MyCalc()
# win = MyCalc2() win.show() sys.exit(app.exec_())