Python GUI教程:信号与槽装饰器@pyqtSlot()

一个简单的例子。实现功能:两个数相加,显示结果。如图

 

Python GUI教程:信号与槽装饰器@pyqtSlot()_第1张图片

一、界面文件 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_())

2.1、装饰器信号与槽的定义格式

@PyQt5.QtCore.pyqtSlot(参数)
def on_发送者对象名称_发射信号名称(self, 参数):
    pass

你可能感兴趣的:(GUI)