Search code examples
pythonpython-3.xgtk3

Custom widget properties in GTK3


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.


Solution

  • 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