将一些工作 PyQt5 代码移植到 PySide2,我有以下内容:
import sys
from PySide2.QtCore import Property, QObject
from PySide2.QtGui import QGuiApplication
class DataPoint(QObject):
def __init__(self, timestamp=0, high=0, low=0, parent=None):
super().__init__(parent)
self._timestamp = timestamp
self._high = high
self._low = low
@Property(float, constant=True)
def timestamp(self):
return self._timestamp
...
这是一个暴露给 QML 引擎的只读数据类。
运行时失败:
Traceback (most recent call last):
line 14, in <module>
class DataPoint(QObject):
line 22, in DataPoint
def timestamp(self):
TypeError: A constant property cannot have a WRITE method or a NOTIFY signal.
最佳答案
这似乎是 PySide2 中的一个错误,它似乎假设如果将 Property 用作 getter 装饰器,则将设置 setter。一个可能的解决方案是不将其用作装饰器,而是在类的范围内使用:
class DataPoint(QObject):
def __init__(self, timestamp=0.0, high=0, low=0, parent=None):
super().__init__(parent)
self._timestamp = timestamp
self._high = high
self._low = low
def timestamp(self):
return self._timestamp
<b>timestamp = Property(float, fget=timestamp, constant=True)</b>
关于python - 类型错误 : A constant property cannot have a WRITE method or a NOTIFY signal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66279370/