TypeError: A constant property cannot have a WRITE method or a NOTIFY signal

Viewed 336

Porting some working PyQt5 code to PySide2, I have the following:

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

    ...

which is a read-only data-class exposed to the QML engine.

Fails at runtime with:

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.
1 Answers

It seems to be a bug in PySide2 that seems to assume that if Property is to be used as a getter decorator then a setter is going to be set. A possible solution is not to use it as a decorator but in the scope of the class:

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

    timestamp = Property(float, fget=timestamp, constant=True)
Related