2

I have a widget like so:

class MyWidget(Gtk.Grid):
    pass

I need to add a custom property to it so that it can be accessed as so:

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

I could use a property decorator in MyWidget and access it like my_widget.my_custom_property = 12 but I'd like for the widget's interface to be consistent with the other library widgets.

eugenhu
  • 1,168
  • 13
  • 22

1 Answers1

5

Gtk widgets are based on GObject. There are examples for subclassing and creating properties, which are easy to put together:

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

Your class can now be used like any other GObject:

my_widget = MyWidget()    
my_widget.props.my_custom_property = 12
my_widget.get_property('my-custom-property'))  # 12
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
  • Just a few questions, is there a way to access the property's default value as defined in the `__gproperties__` dict? Is `GObject.type_register(MyWidget)` necessary since it still works without it? And, what would you use for the min/max values if your property doesn't require bounds? – eugenhu Jan 22 '18 at 14:12
  • @eugenhu Answer overhauled. – Aran-Fey Jan 22 '18 at 14:28
  • Oh wow that's a lot nicer, I was searching on google for something like this, cheers. – eugenhu Jan 22 '18 at 14:36
  • Is there a way to access the custom property in glade? – Olumide Jun 12 '23 at 17:19