pyqt5 添加属性-类方法用属性形式访问
方法一 装饰器法
1 import sys 2 from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QHBoxLayout,QLabel 3 from PyQt5.QtGui import QColor 4 from PyQt5.QtCore import pyqtProperty,Qt 5 6 7 class Demo(QWidget): 8 def __init__(self): 9 super(Demo, self).__init__() 10 self.c=QColor(Qt.red) 11 12 @pyqtProperty(QColor) #获取属性,注意要传入属性的类型 13 def color(self): 14 return self.c 15 16 @color.setter #设置属性 17 def color(self,value): 18 self.c=value 19 20 21 if __name__ == '__main__': 22 app = QApplication(sys.argv) 23 demo = Demo() 24 25 print(demo.color) 26 demo.color=QColor(90,90,90) 27 print(demo.color) 28 29 demo.show() 30 sys.exit(app.exec_())
方法二 函数法
1 import sys 2 from PyQt5.QtWidgets import QApplication, QWidget 3 from PyQt5.QtGui import QColor 4 from PyQt5.QtCore import pyqtProperty,Qt 5 6 class Demo(QWidget): 7 def __init__(self): 8 super(Demo, self).__init__() 9 self.c=QColor(Qt.red) 10 11 def get_color(self): 12 return self.c 13 14 def set_color(self, value): 15 self.c = value 16 17 color = pyqtProperty(QColor, fget=get_color, fset=set_color) #添加属性 18 #第一个参数要填属性的数据类型 19 20 21 if __name__ == '__main__': 22 app = QApplication(sys.argv) 23 demo = Demo() 24 25 print(demo.color) 26 demo.color=QColor(90,90,90) 27 print(demo.color) 28 29 demo.show() 30 sys.exit(app.exec_())