GTK3 中的自定义小部件属性

Custom widget properties in GTK3

我有这样一个小部件:

class MyWidget(Gtk.Grid):
    pass

我需要给它添加一个自定义 属性 以便它可以这样访问:

my_widget = MyWidget()    
my_widget.props.my_custom_property = 12

我可以在 MyWidget 中使用 属性 装饰器并像 my_widget.my_custom_property = 12 一样访问它,但我希望小部件的界面与其他库小部件一致。

Gtk widgets基于GObject. There are examples for subclassing and creating properties,很容易组合起来:

class MyWidget(Gtk.Grid):
    @GObject.Property
    def my_custom_property(self):
        return self._my_custom_property

    @my_custom_property.setter
    def my_custom_property(self, value):
        self._my_custom_property = value

您的 class 现在可以像任何其他 GObject 一样使用:

my_widget = MyWidget()    
my_widget.props.my_custom_property = 12
my_widget.get_property('my-custom-property'))  # 12