• pyqt5界面与逻辑分离--信号槽的装饰器实现方式


     本文展示了 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_())
  • 相关阅读:
    ionic3 生命周期
    java基础中this,super
    LeetCode #26 Remove Duplicates from Sorted Array
    LeetCode #24 Swap Nodes in Pairs
    LeetCode #22 Generate Parentheses
    LeetCode #20 Valid Parentheses
    LeetCode #14 Longest Common Prefix
    iOS CAShapeLayer、CADisplayLink 实现波浪动画效果
    iOS CAEmitterLayer 实现粒子发射动画效果
    iOS CAReplicatorLayer 实现脉冲动画效果
  • 原文地址:https://www.cnblogs.com/hhh5460/p/5390999.html
Copyright © 2020-2023  润新知