Reusing a Gtk.TextTagTable in an object that extends a Gtk.TextBuffer

I have a class that extends a Gtk.TextBuffer and I need reuse a pre-existing Gtk.TextTagTable that is shared with other Gtk.TextBuffer. I tried the code below but the Gtk.TextTagTable passed as parameter is not assigned.

class BufferObject(Gtk.TextBuffer):  # Buffer Object

    __gtype_name__ = 'BufferObject'

    section = GObject.Property(type=object, default=None)
    focused = GObject.Property(type=bool, default=False)

    def __init__(self, section, tag_table):

        super().__init__()

        self.section = section        
        self.tag_table = tag_table

If I created the Gtk.TextBuffer using the Gtk.TextBuffer.new() method it would work, but I don’t know how to do this in a class that extends Gtk.TextBuffer.

Hi,

Gtk.TextBuffer already has a tag-table property, you can set it with
super().init(property=value, ...)

(replace minus - with underscores _ in the property names)

Example:

class BufferObject(Gtk.TextBuffer):  # Buffer Object
    __gtype_name__ = 'BufferObject'

    section = GObject.Property(type=object, default=None)
    focused = GObject.Property(type=bool, default=False)

    def __init__(self, section, tag_table):
        super().__init__(tag_table=tag_table, section=section)
 
# Create object
my_buffer = BufferObject(my_section, my_table)

Alternative,
If you want to use a new constructor:

class BufferObject(Gtk.TextBuffer):  # Buffer Object
    __gtype_name__ = 'BufferObject'

    section = GObject.Property(type=object, default=None)
    focused = GObject.Property(type=bool, default=False)

    @classmethod
    def new(cls, section, tag_table):
        # Call the default constructor
        return cls(tag_table=tag_table, section=section)

# Create object
my_buffer = BufferObject.new(my_section, my_table)

In this 2nd example, we completely skipped the __init__ because we just rely on GObject’s ability to initialize all the parameters from the default constructor’s keyword arguments. But if you need to do some more stuff at init, you can add:

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        # Add other init stuff...
        print("init done")
1 Like

Side note: you can’t access GObject properties like this (it’s for Python attributes):

        # wrong!
        self.section = section
        self.tag_table = tag_table

Instead, you can use GObject’s props mapping:

        #  ok
        self.props.section = section
        self.props.tag_table = tag_table

or generic setters:

        # ok
        self.set_property('section', section)
        self.set_property('tag-table', tag_table)
1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.