PySide2提供了一个Property函数,它允许声明同时表现为Qt和Python属性的属性,并将其setter和getter定义为Python函数。
下面给出了一个简单的示例,说明如何从Python定义和访问Qt属性:
from PySide2.QtCore import QObject,Property
class StudentMsg(QObject):
"""docstring for StudentMsg"""
def __init__(self):
QObject.__init__(self)
def readMsg(self):
return self.msgval
def setMsg(self,msg):
self.msgval = msg
MSG = Property(str,readMsg,setMsg)
student = StudentMsg()
student.MSG = "aaa"
print(student.MSG)
如果要在QML表达式中调用对象的属性,则QML要求属性为在变化时有信号通知。所以需要在上面示例的基础上增加一个信号:
from PySide2.QtCore import QObject,Property,Signal
class StudentMsg(QObject):
"""docstring for StudentMsg"""
def __init__(self):
QObject.__init__(self)
msg_changed = Signal(str)
def readMsg(self):
return self.msgval
def setMsg(self,msg):
self.msgval = msg
self.msg_changed.emit(msg)
MSG = Property(str,readMsg,setMsg,notify = msg_changed)
student = StudentMsg()
student.MSG = "aaa"
print(student.MSG)