Support for Qt Properties

PyQt5不支持设置和获取Qt属性,就好像它们是普通的实例属性一样。这是因为属性的名称经常与属性的getter方法的名称冲突。

但是,PyQt5确实支持在创建实例时使用传递的关键字参数进行属性的初始设置。For example:

act = QAction("&Save", self, shortcut=QKeySequence.Save,
        statusTip="Save the document to disk", triggered=self.save)

该示例还演示了使用关键字参数将信号连接到插槽。

PyQt5还支持使用pyqtConfigure()方法设置属性值(并将信号连接到插槽)。例如,以下给出了与上面相同的结果:

act = QAction("&Save", self)
act.pyqtConfigure(shortcut=QKeySequence.Save,
        statusTip="Save the document to disk", triggered=self.save)

Defining New Qt Properties

可以使用pyqtProperty()函数定义新的Qt属性。它的用法与标准的Python property()函数相同。事实上,以这种方式定义的Qt属性也表现为Python属性。

PyQt5.QtCore.pyqtProperty(type[, fget=None[, fset=None[, freset=None[, fdel=None[, doc=None[, designable=True[, scriptable=True[, stored=True[, user=False[, constant=False[, final=False[, notify=None[, revision=0]]]]]]]]]]]]])

创建一个既可以作为Python属性又可以作为Qt属性的属性。

Parameters:
  • type – the type of the property. It is either a Python type object or a string that is the name of a C++ type.
  • fget – the optional callable used to get the value of the property.
  • fset – the optional callable used to set the value of the property.
  • freset – the optional callable used to reset the value of the property to its default value.
  • fdel – the optional callable used to delete the property.
  • doc – the optional docstring of the property.
  • designable – optionally sets the Qt DESIGNABLE flag.
  • scriptable – optionally sets the Qt SCRIPTABLE flag.
  • stored – optionally sets the Qt STORED flag.
  • user – optionally sets the Qt USER flag.
  • constant – optionally sets the Qt CONSTANT flag.
  • final – optionally sets the Qt FINAL flag.
  • notify – the optional unbound notify signal.
  • revision – the revision exported to QML.
Return type:

the property object.

也可以像使用标准Python property()函数一样使用pyqtProperty()作为装饰器。以下示例显示如何使用getter和setter定义int属性:

from PyQt5.QtCore import QObject, pyqtProperty

class Foo(QObject):

    def __init__(self):
        QObject.__init__(self)

        self._total = 0

    @pyqtProperty(int)
    def total(self):
        return self._total

    @total.setter
    def total(self, value):
        self._total = value

如果你更喜欢Qt术语,你也可以用write来代替setter(和,而不是getter)。